-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSortUsingDutchNAtionalFlag.cpp
More file actions
49 lines (42 loc) · 1.07 KB
/
Copy pathQuickSortUsingDutchNAtionalFlag.cpp
File metadata and controls
49 lines (42 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
// Utility function to swap two elements A[i] and A[j] in the array
void swap(int A[], int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
// Linear-time partition routine to sort an array containing 0, 1 and 2
// It similar to three-way Partitioning for Dutch national flag problem
int QuickSortUsingDutchNAtionalFlag(int A[], int end)
{
int start = 0, mid = 0;
int pivot = 1;
while (mid <= end)
{
if (A[mid] < pivot) // current element is 0
{
swap(A, start, mid);
++start, ++mid;
}
else if (A[mid] > pivot) // current element is 2
{
swap(A, mid, end);
--end;
}
else // current element is 1
{
++mid;
}
}
}
// Sort an array containing 0’s, 1’s and 2’s
int main()
{
int A[] = { 0, 1, 2, 2, 1, 0, 0, 2, 0, 1, 1, 0 };
int n = sizeof(A)/sizeof(A[0]);
QuickSortUsingDutchNAtionalFlag(A, n - 1);
for (int i = 0 ; i < n; i++) {
printf("%d ", A[i]);
}
return 0;
}