Skip to content

Instantly share code, notes, and snippets.

@yavgel85
Last active March 26, 2021 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavgel85/524f7435103a43b23e6a985cd77db263 to your computer and use it in GitHub Desktop.
Save yavgel85/524f7435103a43b23e6a985cd77db263 to your computer and use it in GitHub Desktop.
quickSort #js #algorithm
// Sorts an array of numbers, using the quicksort algorithm.
// Use recursion.
// Use the spread operator (...) to clone the original array, arr.
// If the length of the array is less than 2, return the cloned array.
// Use Math.floor() to calculate the index of the pivot element.
// Use Array.prototype.reduce() and Array.prototype.push() to split the array into two subarrays (elements smaller or equal to the pivot and elements greater than it), destructuring the result into two arrays.
// Recursively call quickSort() on the created subarrays.
const quickSort = arr => {
const a = [...arr];
if (a.length < 2) return a;
const pivotIndex = Math.floor(arr.length / 2);
const pivot = a[pivotIndex];
const [lo, hi] = a.reduce(
(acc, val, i) => {
if (val < pivot || (val === pivot && i != pivotIndex)) {
acc[0].push(val);
} else if (val > pivot) {
acc[1].push(val);
}
return acc;
},
[[], []]
);
return [...quickSort(lo), pivot, ...quickSort(hi)];
};
// Examples
quickSort([1, 6, 1, 5, 3, 2, 1, 4]); // [1, 1, 1, 2, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment