Created
May 16, 2021 21:03
-
-
Save CarlaTeo/2390a6367d9931798fd1352734333662 to your computer and use it in GitHub Desktop.
[JS] Quick Sort
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
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