原理:
每次排序都设置一个low和high ,当前项为x,首先从low开始向后搜索找到一个大于x的记录,然后交换,再从high向前搜索找到小于x的记录,然后交换。一直重复着两步,知道low=high位置,再分别对两个子序列排序,直到每个子序列只含一个记录为止
性能:
代码如下:
let arr = [1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15, 8, 16];
function quickSort(arr, low, high) {
if (low >= high) {
return;
}
let current = arr[low];
//存储初始的low和high
let initLow = low;
let initHigh = high;
while (low < high) {
//找到比当前项小的
while (low < high && arr[high] >= current) {
high--;
}
if (low < high) {
//交换
arr[low] = arr[high]
low++;
}
//找到比当前项大的
while (low < high && arr[low] <= current) {
low++;
}
if (low < high) {
//交换
arr[high] = arr[low]
high--;
}
}
arr[low] = current;
quickSort(arr, initLow, high - 1)
quickSort(arr, high + 1, initHigh)
}