Last active
May 24, 2021 20:45
-
-
Save helabenkhalfallah/be84e4d6ce748f53183756e5f6a8a6b9 to your computer and use it in GitHub Desktop.
Quick Sort (JS)
This file contains hidden or 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
const quickSort = (items) => { | |
if (!items || items.length < 2) { | |
return items | |
} | |
const pivot = items[items.length - 1]; | |
const left = []; | |
const right = []; | |
for (let i = 0; i < items.length - 1; i++) { | |
if (items[i] < pivot) { | |
left.push(items[i]) | |
} else { | |
right.push(items[i]) | |
} | |
} | |
return [ | |
...quickSort(left) || [], | |
pivot, | |
...quickSort(right) || [] | |
] | |
}; | |
const elements = [7, 2, 4, 1, 6, 5, 0, 4, 2]; | |
const sortedElements = quickSort(elements); | |
console.log('sortedElements : ', sortedElements); // [0, 1, 2, 2, 4, 4, 5, 6, 7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment