Sort an array of 0s, 1s and 2s ( Dutch National Flag Algorithm )
PROBLEM :
Write a program to sort an array of 0's,1's and 2's in ascending order.
Input:
The first line contains an integer 'T' denoting the total number of test cases. In each test cases, First line is number of elements in array 'N' and second its values.
Output:
Print the sorted array of 0's, 1's and 2's.
Constraints:
1 <= T <= 100
1 <= N <= 100
0 <= arr[i] <= 2
Example:
Input :
2
5
0 2 1 2 0
3
0 1 0
Output:
0 0 1 2 2
0 0 1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
void swap(int arr[],int a,int b)
{
int temp ;
temp=arr[a] ;
arr[a]=arr[b] ;
arr[b]=temp ;
}
int main()
{
int t ;
cin>>t ;
while(t--)
{
int no ;
cin>>no ;
int arr[no] ;
for(int i=0;i<no;i++)
cin>>arr[i] ;
int s,e,i ;
s=0 ;
e=no-1 ;
i=0 ;
while(i<=e)
{
if(arr[i]==2)
{
swap(arr,i,e) ;
e-- ;
}
else if(arr[i])
i++ ;
else
{
swap(arr,i,s) ;
i++,s++ ;
}
}
for(int i=0;i<no;i++)
cout<<arr[i]<<" " ;
cout<<endl ;
}
return 0;
}
--------------------------------------------------------------------------------
Write a program to sort an array of 0's,1's and 2's in ascending order.
Input:
The first line contains an integer 'T' denoting the total number of test cases. In each test cases, First line is number of elements in array 'N' and second its values.
Output:
Print the sorted array of 0's, 1's and 2's.
Constraints:
1 <= T <= 100
1 <= N <= 100
0 <= arr[i] <= 2
Example:
Input :
2
5
0 2 1 2 0
3
0 1 0
Output:
0 0 1 2 2
0 0 1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
void swap(int arr[],int a,int b)
{
int temp ;
temp=arr[a] ;
arr[a]=arr[b] ;
arr[b]=temp ;
}
int main()
{
int t ;
cin>>t ;
while(t--)
{
int no ;
cin>>no ;
int arr[no] ;
for(int i=0;i<no;i++)
cin>>arr[i] ;
int s,e,i ;
s=0 ;
e=no-1 ;
i=0 ;
while(i<=e)
{
if(arr[i]==2)
{
swap(arr,i,e) ;
e-- ;
}
else if(arr[i])
i++ ;
else
{
swap(arr,i,s) ;
i++,s++ ;
}
}
for(int i=0;i<no;i++)
cout<<arr[i]<<" " ;
cout<<endl ;
}
return 0;
}
--------------------------------------------------------------------------------
Comments
Post a Comment