Skip to content

Commit c6cc818

Browse files
authored
Merge pull request #33 from kumar007ambi/ambikaDSAMastery
Problem on Sorting Algorithm
2 parents 66ecd34 + b810aaa commit c6cc818

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
void closest012(int arr[], int n)
5+
{
6+
int lo = 0, hi = n - 1, mid = 0;
7+
while (mid <= hi)
8+
{
9+
if (arr[mid] == 0)
10+
{
11+
swap(arr[lo], arr[mid]);
12+
lo++;
13+
mid++;
14+
}
15+
else if (arr[mid] == 1)
16+
{
17+
mid++;
18+
}
19+
else
20+
{
21+
swap(arr[mid], arr[hi]);
22+
hi--;
23+
}
24+
}
25+
}
26+
int main()
27+
{
28+
29+
int t;
30+
cin >> t;
31+
while (t--)
32+
{
33+
int n;
34+
cin >> n;
35+
int arr[n];
36+
for (int i = 0; i < n; i++)
37+
{
38+
cin >> arr[i];
39+
}
40+
closest012(arr, n);
41+
for (int i = 0; i < n; i++)
42+
{
43+
cout << arr[i];
44+
}
45+
cout << endl;
46+
}
47+
48+
return 0;
49+
}
50+
51+
// Given an array of 0s, 1s, and 2s. Arrange the array elements such that all 0s come first, followed by all the 1s and then, all the 2s.
52+
// Input: N = 5, arr[] = {0, 2, 1, 2, 0}
53+
// Output: 0 0 1 2 2

0 commit comments

Comments
 (0)