Created
May 23, 2019 06:00
-
-
Save tjeastmond/11a6956b1717ea656815174d3bc51e09 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
// quicksort | |
const quicksort = (arr, left = 0, right = arr.length - 1) => { | |
if (left >= right) return; | |
const pivot = arr[Math.floor((left + right) / 2)]; | |
const index = partition(arr, left, right, pivot); | |
quicksort(arr, left, index - 1); | |
quicksort(arr, index, right); | |
return arr; | |
}; | |
const partition = (arr, left, right, pivot) => { | |
while (left <= right) { | |
while (arr[left] < pivot) left++; | |
while (arr[right] > pivot) right--; | |
if (left <= right) { | |
[arr[left], arr[right]] = [arr[right], arr[left]]; | |
left++; | |
right--; | |
} | |
} | |
return left; | |
}; | |
const array1 = [1, 8, 12, 2, 4, 5, 7, 10, 6, 3, 9, 1]; | |
const array2 = [10, -1, 2, 5, 0, 6, 4, -5]; | |
quicksort(array1); | |
// quicksort(array2); | |
console.log("array1: ", array1); | |
// console.log("array2: ", array2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment