Skip to content

Instantly share code, notes, and snippets.

@helabenkhalfallah
Last active May 24, 2021 20:45
Show Gist options
  • Save helabenkhalfallah/be84e4d6ce748f53183756e5f6a8a6b9 to your computer and use it in GitHub Desktop.
Save helabenkhalfallah/be84e4d6ce748f53183756e5f6a8a6b9 to your computer and use it in GitHub Desktop.
Quick Sort (JS)
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