Sort 0 1 2
You are given an integer array/list(ARR) of size N. It contains only 0s, 1s and 2s. Write a solution to sort this array/list in a 'single scan'.
'Single Scan' refers to iterating over the array/list just once or to put it in other words, you will be visiting each element in the array/list just once.
Note:
Input format :
Output Format :
Constraints :
Sample Input 1:
Sample Output 1:
Sample Input 2:
Sample Output 2:
#include <iostream>
#include <algorithm>
using namespace std;
#include "solution.h"
void sort012(int *arr, int n)
{
int temp[n];
int n0=0;
int n2=n-1;
for(int i=0;i<n;i++){
if(arr[i]==0){
temp[n0]=0;
n0++;
}
else if(arr[i]==2){
temp[n2]=2;
n2--;
}
}
for (int i=n0;i<=n2;i++){
temp[i]=1;
}
for(int i=0;i<n;i++){
arr[i]=temp[i];
}
}
int main()
{
int t;
cin >> t;
while (t--)
{
int size;
cin >> size;
int *arr = new int[size];
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
sort012(arr, size);
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
delete[] arr;
cout << endl;
}
return 0;
}
Comments
Post a Comment