Before that, let’s talk about the concept behind Quicksort. The logic is basically pick a middle point (pivot), bring all the numbers lower than pivot to the left, and numbers larger than pivot to the right. This creates 3 arrays from 1 array. Then you run the same function to the 3 arrays again (this is called recursive function) until all the arrays each contains 1 number. It looks like this:
Did you see a pattern here? We’re running a recursive function that runs until all arrays have a length of 1. Let’s look at the code!
The code is self-explanatory, the if statement looks at the length of the array and determine whether to just return it (if there is only 1 number) or run down to split into 3 arrays (if there are 2 or more numbers). The focus should be on the last line where the less array and greater array are being sorted and all three arrays are added up and pushed up to the last layer, this way the recursive function can get back to the top layer and return the nicely sorted array!
Share with me your way of writing a Quicksort algorithm or a sorting algorithm you write in a different language. I would love to see them!