//快速排序 function QSort(L, low, high) { var pivot; while(low<high) { pivot = Partition(L, low, high);//将L一分为二 QSort(L, low, pivot - 1); low = pivot + 1;//采用迭代而不是递归的方法缩减堆栈深度,从而提高整体性能! } } function swap(L, l, h) { var temp = L[h]; L[h] = L[l]; L[l] = temp; } function Partition(L, low, high) { //三数取中优化算法 防止最小值过大或者过小 var pivotkey,temp; var m = low + (high - low) / 2; m = Math.floor(m); if (L[low] > L[high]) { swap(L, low, high); } if (L[m] > L[high]) swap(L, m, high); if (L[m]>L[low]) swap(L, low, m); pivotkey = L[low]; temp = pivotkey; while (low < high) { while (low<high&&L[high]>=pivotkey) {//找到比pivotkey小的值的下标,然后把当前值赋值给L[low] high--; } L[low] = L[high]; while (low<high&&L[low]<=pivotkey) { low++; } L[high] = L[low]; } L[low] = temp; return low; } var a = [1, 4, 2, 5, 7, 8, 9, 0, 3, 2]; //MereSort(l); //MergeSort2(l); QSort(a, 0, a.length - 1); console.log(a);
时间: 2024-10-10 15:51:46