Skip to content

Commit

Permalink
Merge pull request #33 from kumar007ambi/ambikaDSAMastery
Browse files Browse the repository at this point in the history
Problem on Sorting Algorithm
  • Loading branch information
gautamankoji authored Oct 18, 2024
2 parents 66ecd34 + b810aaa commit c6cc818
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions C++/Data-Structures/02-sorting-algorithms/Closest012.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include <bits/stdc++.h>
using namespace std;

void closest012(int arr[], int n)
{
int lo = 0, hi = n - 1, mid = 0;
while (mid <= hi)
{
if (arr[mid] == 0)
{
swap(arr[lo], arr[mid]);
lo++;
mid++;
}
else if (arr[mid] == 1)
{
mid++;
}
else
{
swap(arr[mid], arr[hi]);
hi--;
}
}
}
int main()
{

int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
closest012(arr, n);
for (int i = 0; i < n; i++)
{
cout << arr[i];
}
cout << endl;
}

return 0;
}

// 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.
// Input: N = 5, arr[] = {0, 2, 1, 2, 0}
// Output: 0 0 1 2 2

0 comments on commit c6cc818

Please sign in to comment.