javascript算法

时间:2022-05-14 15:43:10

代码运行环境: nodejs + mochajs

 /*
*选择排序
*每次查找数组最小数据
*将最小数据排到左侧
*/
var assert = require('assert');
describe('Array', function() {
describe('#indexOf()', function() { var result = [1, 1, 2, 3, 55, 90] it('quickSortTest', function() {
var arr1 = [3, 2, 55, 1, 90, 1]
assert.equal(result.toString(), coolSort.quickSort(arr1).toString());
}); it('bubbleSortTest', function() {
var arr2 = [1, 3, 2, 55, 90, 1] assert.equal(result.toString(), coolSort.selectionsSort(arr2).toString());
}) it('selectionsSortTest', function() {
var arr3 = [1, 55, 2, 3, 90, 1] assert.equal(result.toString(), coolSort.selectionsSort(arr3).toString());
})
});
}); var coolSort = (function() { function compare(arg1, arg2) {
if(arg1 > arg2) {
return 1;
} else if(arg1 === arg2) {
return 0;
} else {
return -1;
}
} function swap(arr, arg1, arg2) {
var temp = arr[arg1];
arr[arg1] = arr[arg2];
arr[arg2] = temp;
} this.selectionsSort = function(arr) {
"use strict";
//判断是否是数组
if(Object.prototype.toString.call(arr) !== "[object Array]") return arr; var len = arr.length,
min = 0,
j = 0,
temp = 0; //判断数组长度
if(len <= 1) return arr; for(var i = 0; i < len -1; i++) { min = i;
//查找出最小的一个数据
for(j = i + 1; j < len; j++) {
if(compare(arr[min], arr[j]) === 1)
min = j;
}
//如果i不是最小的数据,将i与最小数据进行交换
if(min !== i) swap(arr, min, i) } return arr;
} this.quickSort = function(arr) {
"use strict";
if(arr.length <= 1) return arr; var pivotIndex = Math.floor((arr.length / 2));
var pivot = arr.splice(pivotIndex, 1); var left = [];
var right = []; for(var i =0; i < arr.length; i++) {
if(arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
} return quickSort(left).concat(pivot, quickSort(right))
} this.bubbleSort = function (arr) {
"use strict";
var temp = 0,
len = arr.length,
j = 0;
for(var i =0; i < len - 1; i++) {
for(j = 0; j < len - i - 1; j++) {
if(compare(arr[j], arr[j + 1]) === 1 ) {
swap(arr, j , j + 1);
}
}
}
return arr;
} return this;
})()