function swap(arr, i, j) {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
function quickSort(arr, left, right) {
const len = arr.length;
if (left > right) {
return arr;
}
let pivot = arr[left];
let i = left;
let j = right;
while (i != j) {
while (arr[j] >= pivot && i < j) {
j--;
}
while (arr[i] <= pivot && i < j) {
i++;
}
if (i < j && arr[i] !== arr[j]) {
swap(arr, i, j);
}
}
if (left !== i && arr[left] !== arr[i]) {
swap(arr, left, i);
}
quickSort(arr, left, i - 1);
quickSort(arr, i + 1, right);
return arr;
}
let arr = [3, 7, 8, 5, 2, 1, 9, 5, 4];
quickSort(arr, 0, arr.length - 1); // [1, 2, 3, 4, 5, 5, 7, 8, 9]
function swap(arr, i, j) {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
const quickSort = (arr) => {
const stack = [0, arr.length - 1];
while (stack.length > 0) {
const left = stack.pop();
const right = stack.pop();
if (left >= right) {
continue;
}
let i = left;
let j = right;
let p = arr[left];
while (i < j) {
while (i < j && arr[j] >= p) {
j--;
}
while (i < j && arr[i] <= p) {
i++;
}
if (i !== j && arr[i] !== arr[j]) {
swap(arr, i, j);
}
}
stack.push(left, i - 1);
stack.push(i + 1, right);
}
return arr;
};
let arr = [3, 7, 8, 5, 2, 1, 9, 5, 4];
quickSort(arr, 0, arr.length - 1); // [1, 2, 3, 4, 5, 5, 7, 8, 9]