1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| const arr = [3, 7, 8, 4, 5, 1, 2, 6, 9];
const main = () => { quickSort(arr, 0, arr.length - 1); console.log(arr); };
function quickSort(arr, left, right) { if (left < right) { let splitIndex = split(arr, left, right); quickSort(arr, left, splitIndex - 1); quickSort(arr, splitIndex + 1, right); } return arr; }
function split(arr, left, right) { const temp = left; let index = left + 1;
for (let i = index; i <= right; i++) { if (arr[i] < arr[temp]) { swap(arr, i, index); index++; } }
swap(arr, temp, index - 1); return index - 1; }
function swap(arr, i, j) { const temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
main();
|