Over the years, a lot of sorting algorithms have been developed and used in different situations and contexts. However, as time passed, some algorithms started to perform way better than the others in terms of complexity or memory.

Starting with algorithms with an average complexity of O(N²) (Binary Search), we end up with some incredible complexities like O(NlogN). Some of the more popular examples that satisfy this time complexity would be Heap Sort (which was discussed in a previous article), Merge Sort or Quick Sort.

Although all these sorting techniques are widely used in many applications, Quick Sort is considered by many as the best sorting algorithm.

Despite having the time complexity O(NlogN) in best and average case, Quick Sort has O(N²) in worst case scenario. From the other point of view, his competitor, Merge Sort has the O(NlogN) in all three scenarios.

So why is Quick Sort considered better? In practice and real-life problems, this sorting technique manages to get the best time on the average case.

How does Quick Sort work

This algorithm is mainly based around two concepts. One would be the usage of Divide and Conquer, a programming technique that allows you to divide a “problem” into two smaller “problems”.

Moreover, a crucial step in implementing this algorithm is choosing a pivot point in your data. This “pivot” is used to separate the array into 2 different sections.

So, on the left side of the “pivot”, we would put all the elements smaller or equal than his value, whereas on the right side, the elements would be greater than this point.

The way you position your “pivot” can be the difference between a good or bad performance of the algorithm. In this article, I will show you two different implementations : one with a single pivot and other with three pivots.

Understanding the algorithm

After we choose our initial pivot point, we will arrange the elements smaller than the pivot to the left and the elements greater than the pivot to the right. All this should be done in linear time.

The next step you should me is partitioning the array into left and right sub-arrays with respect to the pivot. In this sub-arrays, you need to choose two pivots to be able to constantly repeat the first step.

When your sub-array consists of only one element, obviously it cannot be unsorted, so you stop the recursion.

As you can see, the algorithm could be divided into three different parts :

  • Divide : partition the array with respect to the pivot
  • Conquer : position the elements correctly into the sub-array
  • Combine : let recursion build the solution in logN time

#algorithms #sorting-algorithms #programming #coding #code

Quick Sort: The most performant sorting algorithm
1.25 GEEK