Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem on Sorting Algorithm #33

Merged
merged 2 commits into from
Oct 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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