非递归快速排序
function quickSort(num) {
const list = [[0, num.length - 1]];
while (list.length > 0) {
let now = list.pop();
if (now[0] >= now[1]) {
continue;
}
let i = now[0],
j = now[1],
flag = now[0];
while (i < j) {
while (num[j] >= num[flag] && j > flag) j--;
if (i >= j) break;
while (num[i] <= num[flag] && i < j) i++;
const temp = num[flag];
num[flag] = num[j];
num[j] = num[i];
num[i] = temp;
flag = i;
}
list.push([now[0], flag - 1]);
list.push([flag + 1, now[1]]);
}
return num;
}
console.log(quickSort([4, 6, 3, 2, 1]));
递归法
function quickSort(num, left, right) {
if (left === undefined) left = 0;
if (right === undefined) right = num.length - 1;
if (left >= right) return;
let i = left,
j = right,
flag = left;
while (i < j) {
while (num[j] >= num[flag] && j > flag) j--;
if (i >= j) break;
while (num[i] <= num[flag] && i < j) i++;
const temp = num[flag];
num[flag] = num[j];
num[j] = num[i];
num[i] = temp;
flag = i;
}
quickSort(num, left, flag - 1);
quickSort(num, flag + 1, right);
return num;
}
console.log(quickSort([4, 6, 3, 2, 1]));