Quicksort is a sorting algorithm that is much faster than selection sort. Quicksort involves working with two subarrays as well as a pivot item. When implemented properly it's on average Big O notation is O(n log n). Let’s explore this function and recreate it to sort a array within JavaScript!
Hi Tyler, Firstly, excellent explanation of Big O notation in a relevant way to us JS devs. Secondly, what setup or plugin are you using to display the console logs inline in the editor for an unsaved file? Nicholas.
@Nicholas, it's a vscode plugin called Quokka.js
Why do you use for(let i in array) instead of forEach?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in
Using for...in
to iterate over array eliminates the possibility of using strict type checking.
here's a beautiful more functional version with ramda
:
import { gt, partition } from "ramda";
function quickSort(list) {
if (list.length === 0) {
return list;
} else {
const [pivot, ...rest] = list;
const [left, right] = partition(gt(pivot), rest);
return [...quickSort(left), pivot, ...quickSort(right)];
}
}
const result = quickSort([4, 7, 9, 1, 0, 8, 6, 10, 3, 8, 2, 5]);
console.log(result); // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10]
https://codesandbox.io/s/quicksort-in-ramda-m4br7