Skip to main content

Quick Sort

function partition(arr, start, end){
// Taking the last element as the pivot
const pivotValue = arr[end];
let pivotIndex = start;
for (let i = start; i < end; i++) {
if (arr[i] < pivotValue) {
// Swapping elements
[arr[i], arr[pivotIndex]] = [arr[pivotIndex], arr[i]];
// Moving to next element
pivotIndex++;
}
}

// Putting the pivot value in the middle
[arr[pivotIndex], arr[end]] = [arr[end], arr[pivotIndex]]
return pivotIndex;
};

function quickSort(arr, start, end) {
// Base case or terminating case
if (start >= end) {
return;
}

// Returns pivotIndex
let index = partition(arr, start, end);

// Recursively apply the same logic to the left and right subarrays
quickSort(arr, start, index - 1);
quickSort(arr, index + 1, end);
}

quickSortRecursive(array, 0, array.length - 1)


[2, 5, 6, 9, 1, 8, 3, 5]

start = 0
end = 7

function quicksort(array) {
if (array.length <= 1) {
return array;
}

var pivot = array[0];

var left = [];
var right = [];

for (var i = 1; i < array.length; i++) {
array[i] < pivot ? left.push(array[i]) : right.push(array[i]);
}

return quicksort(left).concat(pivot, quicksort(right));
};

var unsorted = [23, 45, 16, 37, 3, 99, 22];
var sorted = quicksort(unsorted);