希尔排序:
function shellSort(arr) {let len = arr.length;let temp, gap = 1;while(gap < len/3) {gap = gap*3 +1}while(gap >=1) {for(let i = gap;i< len; i++) {temp = arr[i];for( var j= i-gap; j>= 0 && arr[j] > temp; j -= gap) {arr[j + gap] = arr[j];}arr[j + gap] = temp;}gap = (gap -1 ) /3;}return arr
}
let arr=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48];
console.log(shellSort(arr));
归并排序:
function mergeSort(arr){let len = arr.length;if(len < 2){return arr}let middle = Math.floor(len/2);let left = arr.slice(0, middle);let right = arr.slice(middle);return merge(mergeSort(left),mergeSort(right))
}
function merge(left, right) {let results = [];while(left.length && right.length) {if(left[0] < right[0]){results.push(left.shift());} else{results.push(right.shift());}}while(left.length) {results.push(left.shift());}while(right.length) {results.push(right.shift());}return results;
}
var arr=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48];
console.log(mergeSort(arr));
快速排序:
function qSort(arr) {if(arr.length == 0) {return []}let left = [];let right = [];let pivot = arr[0];for(let i =1;i< arr.length;i++) {if(arr[i] < pivot) {left.push(arr[i]);} else{right.push(arr[i]);}}return qSort(left).concat(pivot, qSort(right));
}
var arr=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48];
console.log(qSort(arr));
参考:https://github.com/zoro-web/blog/issues/4