Quick Sort Algorithm

SunJet Liu
Apr 19, 2021

While you are on your Data Structure and Algorithm learning journey you will undoubtably come across the “Quick Sort” algorithm. This week I will attempt to explain this algo the best I can.

function pivot(arr, start = 0, end = arr.length - 1) {
const swap = (arr, idx1, idx2) => {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
};

// We are assuming the pivot is always the first element
let pivot = arr[start];
let swapIdx = start;

for (let i = start + 1; i <= end; i++) {
if (pivot > arr[i]) {
swapIdx++;
swap(arr, swapIdx, i);
}
}

// Swap the pivot from the start the swapPoint
swap(arr, start, swapIdx);
return swapIdx;
}


function quickSort(arr, left = 0, right = arr.length -1){
if(left < right){
let pivotIndex = pivot(arr, left, right) //3
//left
quickSort(arr,left,pivotIndex-1);
//right
quickSort(arr,pivotIndex+1,right);
}
return arr;
}

--

--