Created
March 14, 2023 17:52
-
-
Save fortunee/ce656fb50dfd9c7e03e6439078e0ea44 to your computer and use it in GitHub Desktop.
Quick sort basically picks a pivot element in the given array, sorts it by moving larger items to the right and the smaller elements to the left of the pivot element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* PSEUDOCODE | |
* - initialize the left argument to 0 | |
* - initialize the right argument to array.length | |
* - use the pivot helper fn to get the pivot index pivot(array, right, left) | |
* - recursively call the quickSort fn on both the left and right side of the pivot index | |
* - ONLY if the left is < right index | |
* - hence base case should be if (left < right) { keep calling quickSort recursively } | |
* - when done return array | |
*/ | |
function quickSort(array, left=0, right=array.length) { | |
if (left < right) { | |
const pivotPosition = pivot(array, left, right); | |
quickSort(array, left, pivotPosition-1); | |
quickSort(array, pivotPosition+1, right); | |
} | |
return array; | |
} | |
/** | |
* PSEUDOCODE (pivot helper function) | |
* - set the pivot element with the start argument | |
* - initilize a swap index to be the start argument | |
* - start a loop from the next item following item at the start(+1) | |
* - position of the array to the item at the end postion of the array | |
* - compare each item with the set pivot element | |
* - if any item is smaller than the pivot item then | |
* - increment the swap index and swap that item with | |
* - the pivot element in the array | |
*/ | |
function pivot(array, start=0, end=array.length-1) { | |
let pivotElement = array[start]; | |
let swapIndex = start; | |
for (let i = start + 1; i < end; i++) { | |
if (array[i] < pivotElement) { | |
swapIndex++; | |
swap(array, swapIndex, i); | |
} | |
} | |
swap(array, swapIndex, start); | |
} | |
function swap(array, position1, position2) { | |
let temp = array[position1]; | |
array[position1] = array[position2] | |
array[position2] = temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment