Understanding three way quicksort algorithm


Now that we understand the importance of the three-way quicksort and its advantages and limitations, let's delve into the algorithm used to implement it.

Why is this algorithm also called the Dutch national flag quicksort?
The algorithm is called Dutch national flag quicksort because its partitioning step is similar to the Dutch National Flag Sort (covered in an earlier lesson). Elements less than the pivot are tracked by the left pointer, elements equal to the pivot by the mid pointer, and elements greater than the pivot by the right pointer. This three-way division mirrors how the Dutch National Flag sort separates values into small, mid, and large regions.

Algorithm

The three-way quicksort algorithm operates on an input array containing at least two elements, similar to the standard quicksort. The process begins by selecting a pivot element from the array, which serves as a reference for partitioning the other elements.

Select a random element as the pivot

During the partitioning step, three-way quicksort divides the array into three consecutive segments rather than two. It returns three indices: the first segment contains elements smaller than the pivot, the middle segment contains elements equal to the pivot, and the last segment contains elements greater than the pivot. The middle segment can be ignored in further recursive calls since these elements are already in their correct positions.

Smaller elements go left, equal element to the mid, larger elements go right

After partitioning, the algorithm recursively applies the same procedure only to the subarrays containing elements smaller than and greater than the pivot. This process continues until all subarrays contain either a single element or are empty.

Liking the course? Check our discounted plans to continue learning.