希爾排序javascript
function shellsort(array, gaps) { for (var g = 0; g < gaps.length; g++) { for (var i = gaps[g]; i < array.length; i++) { var temp = array[i]; for (var j = i; (j >= gaps[g]) && (temp < array[j-gaps[g]]);j -= gaps[g]) { array[j] = array[j - gaps[g]]; } array[j] = temp; } console.log(array); } }
間隔序列 gaps能夠動態定義,不過對於大部分的實際應用場景,算法要用到的間隔序列能夠提早定義好,有一些公開定義的間隔序列,使用它們會獲得不一樣的結果。例如Marcin Ciura 在2001 的論文「Best Increments for theAverage Case of Shell Sort」中的間隔序列[701, 301, 132, 57, 23, 10, 4, 1],下一節將介紹具備動態間隔序列的希爾排序.
動態間隔序列希爾排序java
function dynOrdShellsort(array) { var N = array.length; var h = 1; while (h < N/3) {h = 3 * h + 1; } while (h >= 1) { for (var i = h; i < N; i++) { for (var j = i; j >= h && array[j] < array[j-h]; j -= h) { // swap(array, j, j-h); [array[j], array[j-h]] = [array[j-h], array[j]]; } }h = (h-1)/3; } }
在《算法(第 4 版)》(人郵版)的合著者 Robert Sedgewick 定義了一個 shellsort() 函數,在這個函數中能夠經過一個公式來對希爾排序用到的間隔序列進行動態計算。Sedgewick 的算法是經過上面的代碼片斷來決定初始間隔值的,並添加到外層 for 循環.
歸併排序算法
let mergeSort = (function () { function mergeSort(arr) { if (arr.length < 2) { return; } var step = 1; var left, right; while (step < arr.length) { left = 0; right = step; while (right + step <= arr.length) { mergeArrays(arr, left, left+step, right, right+step); left = right + step; right = left + step; } if (right < arr.length) { mergeArrays(arr, left, left+step, right, arr.length); } step *= 2; } } function mergeArrays(arr, startLeft, stopLeft, startRight, stopRight) { var rightArr = new Array(stopRight - startRight + 1); var leftArr = new Array(stopLeft - startLeft + 1); k = startRight; for (var i = 0; i < (rightArr.length-1); ++i) { rightArr[i] = arr[k]; ++k; } k = startLeft; for (var i = 0; i < (leftArr.length-1); ++i) { leftArr[i] = arr[k]; ++k; } rightArr[rightArr.length-1] = Infinity; // 哨兵值 leftArr[leftArr.length-1] = Infinity; // 哨兵值 var m = 0; var n = 0; for (var k = startLeft; k < stopRight; ++k) { if (leftArr[m] <= rightArr[n]) { arr[k] = leftArr[m]; m++; } else { arr[k] = rightArr[n]; n++; } } // console.log("left array - ", leftArr); // console.log("right array - ", rightArr); } return mergeSort; })()
快速排序shell
function qSort(arr){ if (arr.length == 0) { return []; } var left = []; var right = []; var pivot = arr[0]; for (var 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)); }