Created
February 1, 2021 19:24
-
-
Save ayrusme/77adbc579df630291eebc02215763d5d to your computer and use it in GitHub Desktop.
This file contains 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
function partition(arr, low, high) { | |
let pivot = arr[high]; | |
let i = low - 1; | |
for (let j = low; j < high; j++) { | |
if (arr[j] <= pivot) { | |
// if the current element is less than or equal to the pivot, | |
// increment i and then swap the current element with arr[i] | |
i++; | |
[arr[i], arr[j]] = [arr[j], arr[i]]; | |
} | |
} | |
// Now let us swap the elements arr[i+1] and pivot (arr[high]) | |
// to place the pivot in the right place. | |
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]]; | |
// returning the pivot's index to the caller to indicate that partition is done | |
return i + 1; | |
} | |
function quickSort(arr, low, high) { | |
if (low >= high) { | |
return; | |
} | |
let pivotIndex = partition(arr, low, high); | |
// now that we have the pivot's index, | |
// let's recursively go through the sub arrays till all of them are sorted | |
quickSort(arr, low, pivotIndex - 1); | |
quickSort(arr, pivotIndex + 1, high); | |
} | |
// populate the array with random 100k integers | |
let arr = []; | |
while (arr.length < 100000) { | |
arr.push(~~(Math.random() * 100000)); | |
} | |
console.log(`starting with array with length ${arr.length}`); | |
console.time("quickSort"); | |
quickSort(arr, 0, arr.length - 1); | |
console.timeEnd("quickSort"); | |
console.log(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment