Created
January 27, 2022 02:12
-
-
Save kevinjie/f26e606dc6a38382d09eca26f6e68933 to your computer and use it in GitHub Desktop.
quickSort
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
export default function sort(originalArray) { | |
const array = [...originalArray] | |
if (array.length <= 1) { | |
return array | |
} | |
const pivot = array.shift() | |
const centerArray = [pivot] | |
const leftArray = [] | |
const rightArray = [] | |
while(array.length) { | |
let element = array.shift() | |
if (element === pivot) { | |
centerArray.push(element) | |
} else if (element < pivot) { | |
leftArray.push(element) | |
} else { | |
rightArray.push(element) | |
} | |
} | |
const leftSortedArray = sort(leftArray) | |
const rightSortedArray = sort(rightArray) | |
return [ | |
...leftSortedArray, | |
...centerArray, | |
...rightSortedArray | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment