Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created May 16, 2021 21:03
Show Gist options
  • Save CarlaTeo/2390a6367d9931798fd1352734333662 to your computer and use it in GitHub Desktop.
Save CarlaTeo/2390a6367d9931798fd1352734333662 to your computer and use it in GitHub Desktop.
[JS] Quick Sort
function quickSort(array) {
if(array.length <= 1) return array;
const pivot = array[0];
const [left, right] = pivotDivision(array.slice(1), pivot);
return [...quickSort(left), pivot, ...quickSort(right)];
}
function pivotDivision(array, pivot) {
const left = [];
const right = [];
array.forEach(value => {
if(value <= pivot) left.push(value);
else right.push(value);
});
return [left, right];
}
// ------------------------- Test -----------------------------------------//
const array = [8, 7, 1, 6, 9, 4, 8];
console.log(quickSort(array)); // [1, 4, 6, 7, 8, 8, 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment