Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
3-Way QuickSort (Dutch National Flag)
The 3-Way QuickSort, also known as the Dutch National Flag algorithm, is an optimized version of the standard QuickSort algorithm. While traditional QuickSort partitions the array into two parts (less than and greater than pivot), 3-Way QuickSort creates three partitions: elements less than pivot, equal to pivot, and greater than pivot.
Syntax
void partition(int arr[], int left, int right, int *i, int *j); void quicksort3Way(int arr[], int left, int right);
Algorithm
The partition function divides the array into three sections −
partition(arr, left, right, i, j):
if right - left <= 1:
if arr[right] < arr[left]:
swap arr[right] and arr[left]
i = left, j = right
return
mid = left, pivot = arr[right]
while mid <= right:
if arr[mid] < pivot:
swap arr[left] and arr[mid]
increment left and mid
else if arr[mid] == pivot:
increment mid
else:
swap arr[mid] and arr[right]
decrement right
i = left - 1, j = mid
Example
Here's a complete implementation of 3-Way QuickSort in C −
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void partition(int arr[], int left, int right, int *i, int *j) {
if (right - left <= 1) {
if (arr[right] < arr[left])
swap(&arr[right], &arr[left]);
*i = left;
*j = right;
return;
}
int mid = left;
int pivot = arr[right];
while (mid <= right) {
if (arr[mid] < pivot) {
swap(&arr[left], &arr[mid]);
left++;
mid++;
} else if (arr[mid] == pivot) {
mid++;
} else {
swap(&arr[mid], &arr[right]);
right--;
}
}
*i = left - 1;
*j = mid;
}
void quicksort3Way(int arr[], int left, int right) {
if (left >= right)
return;
int i, j;
partition(arr, left, right, &i, &j);
quicksort3Way(arr, left, i);
quicksort3Way(arr, j, right);
}
void display(int arr[], int n) {
for (int k = 0; k < n; k++)
printf("%d ", arr[k]);
printf("<br>");
}
int main() {
int a[] = {4, 9, 4, 3, 1, 9, 4, 3, 9, 4, 3, 1, 4};
int n = sizeof(a) / sizeof(int);
printf("Original array: ");
display(a, n);
quicksort3Way(a, 0, n - 1);
printf("Sorted array: ");
display(a, n);
return 0;
}
Original array: 4 9 4 3 1 9 4 3 9 4 3 1 4 Sorted array: 1 1 3 3 3 4 4 4 4 4 9 9 9
Key Advantages
- Better performance for arrays with many duplicate elements
- Optimal handling of equal elements by grouping them together
- Reduces recursive calls compared to standard QuickSort when duplicates are present
Conclusion
3-Way QuickSort is particularly efficient for datasets with many duplicate values. It partitions the array into three sections, ensuring equal elements are grouped together, which reduces the number of recursive calls and improves overall performance.
