Last active
July 28, 2019 07:18
-
-
Save motss/db131f9a667d44c33084bff2355080d0 to your computer and use it in GitHub Desktop.
Sorting algorithms
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
{ | |
// Reference: https://bit.ly/2yjWDeY | |
// Time complexity: O(n log n) on average or O(n^2) for worst-case | |
// Space complexity: O(n) | |
function quickSort(list) { | |
if (list.length < 2) return list; | |
const left = []; | |
const right = []; | |
const pivot = list.shift(); | |
const len = list.length; | |
let i = 0; | |
while (i < len) { | |
const val = list[i]; | |
if (val <= pivot) left.push(val); | |
else right.push(val); | |
i += 1; | |
} | |
return quickSort(left).concat(pivot, quickSort(right)); | |
} | |
a = [1, 4, 6, 8, 2, 3, 7, -1, 0]; | |
b = [...a]; | |
console.time('quickSort'); | |
quickSort(b); | |
console.timeEnd('quickSort'); | |
c = [...a]; | |
console.time('sort'); | |
c.sort(); | |
console.timeEnd('sort'); | |
quickSort([...a]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment