Skip to content

Instantly share code, notes, and snippets.

@ayrusme
Created February 1, 2021 19:24
Show Gist options
  • Save ayrusme/77adbc579df630291eebc02215763d5d to your computer and use it in GitHub Desktop.
Save ayrusme/77adbc579df630291eebc02215763d5d to your computer and use it in GitHub Desktop.
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