Last active
July 6, 2017 04:29
-
-
Save colus001/8fb63163ef2b3bef36de13889abb0115 to your computer and use it in GitHub Desktop.
Quick Sort in Javascript
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
// QUICK SORT ALGORITHM | |
// @params {Array} arr | |
// @returns {Array} arr | |
const quickSort = (arr) => { | |
if (arr.length < 2) return arr | |
const pivotIndex = Math.floor(Math.random() * arr.length) | |
const pivot = arr[pivotIndex], less = [], greater = [] | |
for (let i = 0, l = arr.length; i < l; i++) { | |
if (i === pivotIndex) continue | |
if (arr[i] <= pivot) less.push(arr[i]) | |
else greater.push(arr[i]) | |
} | |
return [ | |
...quickSort(less), | |
pivot, | |
...quickSort(greater), | |
] | |
} | |
// TEST CASE | |
const TEST_CASE = [5, 30, 23, 0, 12, 1] | |
const TEST_RESULT = [0, 1, 5, 12, 23, 30] | |
const sorted = quickSort(TEST_CASE) | |
const arrayMatch = (arr, tar) => { | |
if (arr.length !== tar.length) return false | |
for (let i = 0, l = arr.length; i < l; i++) { | |
if (arr[i] !== tar[i]) return false | |
} | |
return true | |
} | |
if (!arrayMatch(sorted, TEST_RESULT)) { | |
console.log({ | |
sorted, | |
target: TEST_RESULT, | |
}) | |
throw new Error('FAILED!') | |
} | |
console.info('SUCCESS!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment