VOOZH about

URL: https://www.geeksforgeeks.org/dsa/3-way-quicksort-dutch-national-flag/

⇱ 3-Way QuickSort (Dutch National Flag) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

3-Way QuickSort (Dutch National Flag)

Last Updated : 23 Jul, 2025

In simple QuickSort algorithm, we select an element as pivot, partition the array around a pivot and recur for subarrays on the left and right of the pivot. 
Consider an array which has many redundant elements. For example, {1, 4, 2, 4, 2, 4, 1, 2, 4, 1, 2, 2, 2, 2, 4, 1, 4, 4, 4}. If 4 is picked as a pivot in Simple Quick Sort, we fix only one 4 and recursively process remaining occurrences.
The idea of 3 way Quick Sort is to process all occurrences of the pivot and is based on Dutch National Flag algorithm. 

In 3 Way QuickSort, an array arr[l..r] is divided in 3 parts:
a) arr[l..i] elements less than pivot.
b) arr[i+1..j-1] elements equal to pivot.
c) arr[j..r] elements greater than pivot.


Below is the implementation of the above algorithm.


Output
4 9 4 4 1 9 4 4 9 4 4 1 4 
1 1 4 4 4 4 4 4 4 4 9 9 9 

Time Complexity:

Where 'N' is the number of elements in the given array/list

The average number of recursive calls made to the quicksort function is log N, and every time the function is called we are traversing the given array/list which requires O(N) time. Thus, the total time complexity is O(N * log (N)).

Space Complexity:

where ā€˜N’ is the number of elements in the given array/list.


Thanks to Utkarsh for suggesting above implementation.

Another Implementation using Dutch National Flag Algorithm


Output
4 9 4 4 1 9 4 4 9 4 4 1 4 
1 1 4 4 4 4 4 4 4 4 9 9 9 

Time Complexity: O(N2) The time complexity for this code is O(N*log(N)) in the average and best-case scenarios, and O(N^2) in the worst-case scenario.

Space Complexity: O(log N)
Thanks Aditya Goel for this implementation.
Reference: 
https://algs4.cs.princeton.edu/lectures/23DemoPartitioning.pdf 
http://www.sorting-algorithms.com/quick-sort-3-way
 

Comment
Article Tags: