forked from Dexter-99/Hacktober-Fest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortAnArraysOf012.cpp
79 lines (78 loc) · 1.03 KB
/
SortAnArraysOf012.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <bits/stdc++.h>
using namespace std;
void naive(int a[], int n)
{
sort(a, a + n);
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void better(int a[], int n)
{
int z = 0;
int o = 0;
int t = 0;
for (int i = 0; i < n; i++)
{
if (a[i] == 0)
z++;
else if (a[i] == 1)
o++;
else
{
t++;
}
}
int idx = 0;
while (z--)
{
a[idx++] = 0;
}
while (o--)
{
a[idx++] = 1;
}
while (t--)
{
a[idx++] = 2;
}
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}
// Dutch National Flag Algorithm
void optimal(int a[], int n)
{
int low=0,mid=0,high=n-1;
while(mid<=high)
{
if(a[mid]==0)
{
swap(a[mid++],a[low++]);
}
else if(a[mid]==1)
{
mid++;
}
else
{
swap(a[mid],a[high--]);
}
}
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
int main()
{
int n = 5;
int a[n ] = {1,0,0,2,0};
// naive(a, n);
// better(a, n);
optimal(a, n);
return 0;
}