Skip to content

Instantly share code, notes, and snippets.

@patmood
Last active February 27, 2019 16:41
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 patmood/1e789a668699ea1eded2155416053c37 to your computer and use it in GitHub Desktop.
Save patmood/1e789a668699ea1eded2155416053c37 to your computer and use it in GitHub Desktop.
Javascript Quicksort
// Quicksort
// Time: O(n log(n))
// Space: O(log(n))
const test = require('assert').deepEqual
const quickSort = (arr) => {
if (arr.length <= 1) return arr
const pivotIndex = arr.length - 1
const pivotVal = arr[pivotIndex]
const left = []
const right = []
arr.slice(0, pivotIndex).forEach(val => {
val < pivotVal ? left.push(val) : right.push(val)
})
return quickSort(left).concat([pivotVal], quickSort(right))
}
test(quickSort([1]), [1])
test(quickSort([2, 1]), [1, 2])
test(quickSort([2, 1, -1]), [-1, 1, 2])
test(quickSort([2, 1, -1, 0.23]), [-1, 0.23, 1, 2])
@patmood
Copy link
Author

patmood commented Feb 27, 2019

Note that this creates new arrays, should reorder in-place for improved space complexity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment