QuickSort

Crystal Villanueva
2 min readAug 16, 2021

Let me tell you about one of the most efficient algorithms to sort an array of items — it’s called QuickSort (Obvi).

It’s shorter than Merge Sort in terms of writing the code (less code is best code, right?). Whereas Merge Sort takes needs a helper function to compare each individual array to each other and merge it, Quick Sort just needs one function for it all.

It’s time complexity is O (n log n). Which means it’s muy eficiente. This algorithm compares each item to the next, sorts the two, then it compares the next two items and sorts the two… so on and so forth: comparing and sorting.

Quick Sort uses a pivot item. It takes the first item in the array using shift(). Then, using the first item in the array, it continuously compares each item to the pivot item.

In the end, we concatenate the our results with two arrays that we instantiated in the beginning and the pivot. In the resultant array, we recursively call the function to continue sorting. If one of the instantiated arrays (with an recursive argument) is empty, the spread operator will ignore it and still return the resultant array.

Here is the code for Quick Sort!

function quickSort(array) {   //base case   if (array.length <= 1) return array;   //create the first element for the array, and two empty arrays   let pivot = array.shift();   let less = [];   let greater = [];   //loop through the array   for (let ele of array) {       let value = array[ele];       value <= pivot ? less.push(value) : greater.push(value);
}
//return the concatenated recursive array using the spread operator. return [...quickSort(less), pivot, ...quickSort(greater)];}//Big O is o (n log n). This means that the algorithm is very efficient.quickSort([3, 5, 4, 2, 2, 9, 8, 77]);

I hope this helps.

Happy Hacking!

-Crystal

--

--