Skip to content

Instantly share code, notes, and snippets.

@Killea
Forked from claudiahdz/QuickSort.js
Last active July 31, 2022 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Killea/b423c1a358c9f0cba7aba09a15c687b1 to your computer and use it in GitHub Desktop.
Save Killea/b423c1a358c9f0cba7aba09a15c687b1 to your computer and use it in GitHub Desktop.
// Find a "pivot" element in the array to compare all other
// elements against and then shift elements before or after
// pivot depending on their values
const qucikSort = (arr, left = 0, right = arr.length - 1) => {
if (arr.length > 1) {
const index = partition(arr, left, right)
if (left < index - 1) {
qucikSort(arr, left, index - 1)
}
if (index < right) {
qucikSort(arr, index, right)
}
}
return arr
}
const partition = (arr, l, r) => {
let pivot = arr[Math.floor((r + l) / 2)],
left = l, // Start pointer at the first item in the array
right = r // Start pointer at the last item in the array
while (left <= right) {
// Move left pointer to the right until the value at the
// left is greater than the pivot value
while (arr[left] < pivot) {
left++
}
// Move right pointer to the left until the value at the
// right is less than the pivot value
while (arr[right] > pivot) {
right--
}
// If the left pointer is less than or equal to the
// right pointer, then swap values
if (left <= right) {
[arr[left], arr[right]] = [arr[right], arr[left]] // ES6 destructuring swap
left++
right--
}
}
return left
}
// console.log(qucikSort([32,3,0,-1,2,3,54,7,32,3,0,-1,2,3,54,7,888,2,-22,-999]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment