代码运行环境: nodejs + mochajs
1 /* 2 *选择排序 3 *每次查找数组最小数据 4 *将最小数据排到左侧 5 */ 6 var assert = require('assert'); 7 describe('Array', function() { 8 describe('#indexOf()', function() { 9 10 var result = [1, 1, 2, 3, 55, 90] 11 12 it('quickSortTest', function() { 13 var arr1 = [3, 2, 55, 1, 90, 1] 14 assert.equal(result.toString(), coolSort.quickSort(arr1).toString()); 15 }); 16 17 it('bubbleSortTest', function() { 18 var arr2 = [1, 3, 2, 55, 90, 1] 19 20 assert.equal(result.toString(), coolSort.selectionsSort(arr2).toString()); 21 }) 22 23 it('selectionsSortTest', function() { 24 var arr3 = [1, 55, 2, 3, 90, 1] 25 26 assert.equal(result.toString(), coolSort.selectionsSort(arr3).toString()); 27 }) 28 }); 29 }); 30 31 var coolSort = (function() { 32 33 function compare(arg1, arg2) { 34 if(arg1 > arg2) { 35 return 1; 36 } else if(arg1 === arg2) { 37 return 0; 38 } else { 39 return -1; 40 } 41 } 42 43 function swap(arr, arg1, arg2) { 44 var temp = arr[arg1]; 45 arr[arg1] = arr[arg2]; 46 arr[arg2] = temp; 47 } 48 49 this.selectionsSort = function(arr) { 50 "use strict"; 51 //判断是否是数组 52 if(Object.prototype.toString.call(arr) !== "[object Array]") return arr; 53 54 var len = arr.length, 55 min = 0, 56 j = 0, 57 temp = 0; 58 59 //判断数组长度 60 if(len <= 1) return arr; 61 62 63 for(var i = 0; i < len -1; i++) { 64 65 min = i; 66 //查找出最小的一个数据 67 for(j = i + 1; j < len; j++) { 68 if(compare(arr[min], arr[j]) === 1) 69 min = j; 70 } 71 //如果i不是最小的数据,将i与最小数据进行交换 72 if(min !== i) swap(arr, min, i) 73 74 } 75 76 return arr; 77 } 78 79 this.quickSort = function(arr) { 80 "use strict"; 81 if(arr.length <= 1) return arr; 82 83 var pivotIndex = Math.floor((arr.length / 2)); 84 var pivot = arr.splice(pivotIndex, 1); 85 86 var left = []; 87 var right = []; 88 89 for(var i =0; i < arr.length; i++) { 90 if(arr[i] < pivot) { 91 left.push(arr[i]); 92 } else { 93 right.push(arr[i]); 94 } 95 } 96 97 return quickSort(left).concat(pivot, quickSort(right)) 98 } 99 100 this.bubbleSort = function (arr) { 101 "use strict"; 102 var temp = 0, 103 len = arr.length, 104 j = 0; 105 for(var i =0; i < len - 1; i++) { 106 for(j = 0; j < len - i - 1; j++) { 107 if(compare(arr[j], arr[j + 1]) === 1 ) { 108 swap(arr, j , j + 1); 109 } 110 } 111 } 112 return arr; 113 } 114 115 return this; 116 })()