快速排序
function quicksort(arr) {if (arr.length <= 1) return arr;let midIndex = arr.length >> 1;let mid = arr.splice(midIndex, 1)[0];// [4, 3, 5, 2, 1, 6]console.log(midIndex,mid);let left = [];let right = [];for (let i = 0; i < arr.length; i++) {if (arr[i] <= mid) {left.push(arr[i])} else {right.push(arr[i])}}return quicksort(left).concat(mid, quicksort(right))}console.log(quicksort([4, 3, 5, 2, 1, 6])); // [1, 2, 3, 4, 5, 6]
归并排序
function merge(left,right){let res=[]while(left.length>0 && right.length>0){if(left[0]<right[0]){res.push(left.shift())}else{res.push(right.shift())}}return res.concat(left).concat(right)}function mergeSort(arr){if(arr.length==1) return arr// let mid=Math.floor(arr.length/2)let mid= arr.length>>1let left=arr.slice(0,mid)let right=arr.slice(mid)return merge(mergeSort(left),mergeSort(right))}console.log(mergeSort([3,2,4,5,1,7,6]));
插入排序
function insertSort(arr) {for (let i = 1; i < arr.length; i++) {let j = i - 1const tmp = arr[i]while (j >= 0 && arr[j] > tmp) {arr[j + 1] = arr[j]// 移动j--}// 放入合适位置arr[j + 1] = tmp}return arr}console.log(insertSort([3, 2, 4, 5, 1, 6]));
选择排序
function selectSort(arr){for(let i=0;i<arr.length;i++){let minIndex=ifor(let j=i+1;j<arr.length;j++){if(arr[j]<arr[minIndex]){minIndex=j}}const tmp=arr[i]arr[i]=arr[minIndex]arr[minIndex]=tmp}return arr}console.log(selectSort([3,2,4,5,1,7,6]));
希尔排序
function shellSort(array) {const len = array.length;let gap = Math.floor(len / 2);for (gap; gap > 0; gap = Math.floor(gap / 2)) {for (let i = gap; i < len; i++) {let j = i - gap;const temp = array[i];while (j >= 0 && array[j] > temp) {array[j + gap] = array[j];j -= gap;}array[j + gap] = temp;}}return array;}
堆排序
function heapSort(array) {for (let i = Math.floor(array.length / 2 - 1); i >= 0; i--) {adjustHeap(array, i, array.length);}for (let j = array.length - 1; j > 0; j--) {const temp = array[0];array[0] = array[j];array[j] = temp;adjustHeap(array, 0, j);}return array;}function adjustHeap(array, i, length) {for (let j = 2 * i + 1; j < length; j = 2 * j + 1) {const temp = array[i];if (j + 1 < length && array[j] < array[j + 1]) {j++;}if (temp < array[j]) {array[i] = array[j];array[j] = temp;i = j;} else break;}}
