-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathCS_6_Sort012.cpp
47 lines (44 loc) · 896 Bytes
/
CS_6_Sort012.cpp
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
// Dutch national flag algorithm
// Space: constant
// Time: O(n), better, not optimal
#include <iostream>
using namespace std;
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void sort012(int arr[], int n)
{
int low = 0, mid = 0, high = n - 1;
while (mid <= high)
{
if (arr[mid] == 0)
{
swap(arr[mid], arr[low]);
low++;
mid++;
}
else if (arr[mid] == 1)
mid++;
else
{
swap(arr[mid], arr[high]);
high--;
}
}
}
int main()
{
int arr[] = {0, 1, 2, 2, 1, 0};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"Array before sorting: "<<endl;
printArray(arr, n);
sort012(arr, n);
cout<<"Array after sorting: "<<endl;
printArray(arr, n);
return 0;
}