A Rather Easy Way to Implement Quicksort in JavaScript
May 23, 2019
left
and right
(or anything you want to call them). After comparing each element to pivot, push it to left
if it's smaller or right
if it's bigger than pivot. Then return [...quickSort(left), pivot, ...quickSort(right)]
will do the magic.function quickSort(arr) {
if (arr.length <= 1) return arr;
else {
let pivot = arr.pop();
let len = arr.length;
let left = [];
let right = [];
for (let i = 0; i < len; i++) {
if (arr[i] >= pivot) right.push(arr[i]);
else left.push(arr[i]);
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
}