Skip to content

Commit 44eeb3d

Browse files
authored
Merge pull request div-bargali#539 from muskanlalit18/main
Add Sort 0 1 2 Technique
2 parents 3cebd01 + a5a21e3 commit 44eeb3d

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
//Demonstration of the Sort 0 1 2 Technique using 3 pointers.
2+
//index 0 - (low - 1) represent all the 0s
3+
//index low - (mid - 1) represent all the 1s
4+
//index high - (n-1) represent all the 2s
5+
//Example:
6+
// Initially: 0 1 2 1 2 0 1
7+
// Finally:
8+
// 0 0 1 1 1 1 2 2
9+
// | |
10+
// | |
11+
// low mid & high
12+
13+
//Test cases:
14+
/*
15+
3
16+
5
17+
1 0 0 1 2
18+
0 0 1 1 2
19+
8
20+
0 0 1 0 1 2 2 1
21+
0 0 0 1 1 1 2 2
22+
3
23+
0 1 0
24+
0 0 1
25+
*/
26+
27+
#include <bits/stdc++.h>
28+
using namespace std;
29+
30+
void swap(int* a, int* b)
31+
{
32+
int temp = *a;
33+
*a = *b;
34+
*b = temp;
35+
}
36+
37+
int main()
38+
{
39+
int test_cases;
40+
cin>>test_cases;
41+
while(test_cases--)
42+
{
43+
int n;
44+
cin>>n;
45+
int arr[n];
46+
for(int i = 0; i<n; i++)
47+
{
48+
cin>>arr[i];
49+
}
50+
int low = 0, mid = 0, high = n-1;
51+
52+
//We use the mid pointer to traverse through the array
53+
while(mid<=high)
54+
{
55+
if(arr[mid]==0)
56+
{
57+
swap(arr[mid++], arr[low++]);
58+
59+
}
60+
else if(arr[mid]==1)
61+
{
62+
mid++;
63+
}
64+
else if(arr[mid]==2)
65+
{
66+
swap(arr[mid], arr[high]);
67+
high--;
68+
}
69+
}
70+
71+
for(int i = 0; i<n; i++)
72+
{
73+
cout<<arr[i]<<" ";
74+
}
75+
cout<<endl;
76+
}
77+
78+
return 0;
79+
}

0 commit comments

Comments
 (0)