Skip to content

Instantly share code, notes, and snippets.

@kevinjie
Created January 27, 2022 02:12
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 kevinjie/f26e606dc6a38382d09eca26f6e68933 to your computer and use it in GitHub Desktop.
Save kevinjie/f26e606dc6a38382d09eca26f6e68933 to your computer and use it in GitHub Desktop.
quickSort
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