Quick Sort Implementation
The recursive version of quick sort is very easy to implement, and is shown in the right box. See how elegant and easy it is?
Most people looking at the code can meaningfully understand the "concept" behind quick sort
. It first adjusts items around the pivot, and then calls quickSort
recursively on both left and right subarrays.
xxxxxxxxxx
42
console.log(vect);
function exchange(a, i, j) {
let temp = a[i];
a[i] = a[j];
a[j] = temp;
}
​
function adjust(A, start, end, pivot) {
let a = start, b = end;
let stop = false;
while (!stop) {
while (a < pivot && A[a] <= A[pivot])
a++;
while (b > pivot && A[b] >= A[pivot])
b--;
if (a >= pivot && b <= pivot)
stop = true;
else {
exchange(A, a, b);
if (a === pivot)
pivot = b;
else if (b === pivot)
pivot = a;
}
}
}
​
function quickSortRecursive(A, start, end) {
if (end - start < 0)
return;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment