1 //5. 希尔排序 2 var shellSort = function(arr) { 3 var len = arr.length; 4 for (var gap = Math.floor(len / 2); gap > 0; gap = Math.floor(gap / 2)) { 5 for (var i = gap; i < len; i++) { 6 var temp = arr[i], 7 j = i - gap; 8 while (temp < arr[j] && j > -1) { 9 arr[j + gap] = arr[j]; 10 j -= gap; 11 } 12 arr[j + gap] = temp; 13 } 14 } 15 return arr; 16 }; 17 18 //6. 归并排序 19 function mergeSort(source, dest, s, t) { 20 var m, dest2 = new Array(); 21 if (s == t) { 22 dest[s] = source[s]; 23 } else { 24 m = Math.floor((s + t) / 2); 25 mergeSort(source, dest2, s, m); 26 mergeSort(source, dest2, m + 1, t); 27 merge(dest2, dest, s, m, t); 28 } 29 } 30 31 function merge(source, dest, s, m, n) { 32 for (var i = m + 1, k = s; i <= n && s <= m; k++) { 33 if (source[s] < source[i]) { 34 dest[k] = source[s++]; 35 } else { 36 dest[k] = source[i++]; 37 } 38 } 39 40 if (s <= m) { 41 for (var l = 0; l <= m - s; l++) { 42 dest[k + l] = source[s + l]; 43 } 44 } 45 if (i<= n) { 46 for (var l = 0; l <= n - i; l++) { 47 dest[k + l] = source[i + l]; 48 } 49 50 } 51 } 52 53 //7. 堆排序 54 var heapSort = function(arr) { 55 var temp, len = arr.length; 56 for (var i = Math.floor(len / 2); i >= 0; i--) { 57 heapAdjust(arr, i, len - 1); 58 } 59 for (var i = len - 1; i >= 0; i--) { 60 arraySwap(arr, 0, i); 61 heapAdjust(arr, 0, i - 1); 62 } 63 return arr; 64 }; 65 66 var heapAdjust = function(arr, start, max) { 67 var temp = arr[start]; 68 for (var i = 2 * start; i < max; i *= 2) { 69 if (i < max && arr[i] < arr[i + 1]) { 70 ++i; 71 } 72 if (temp >= arr[i]) { 73 break; 74 } 75 arr[start] = arr[i]; 76 start = i; 77 } 78 arr[start] = temp; 79 };