Last active
February 27, 2019 16:41
-
-
Save patmood/1e789a668699ea1eded2155416053c37 to your computer and use it in GitHub Desktop.
Javascript Quicksort
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 | |
// 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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that this creates new arrays, should reorder in-place for improved space complexity