SHIFT ALL 0s TO FRONT & 2s AT LAST OF ARRAY WITHOUT USING SORT LOGIC IN C++

#include<iostream>
using namespace std;

void shiftNumbers(int a[],int n)
{
int i,j,k,tmp;
for(i=0,j=0;i<n;i++)
{
if(a[i]==0)
{
tmp=a[j];
a[j]=a[i];
a[i]=tmp;
j++;
}
}
for(i=j;i<n;i++)
{
if(a[i]==1)
{
tmp=a[j];
a[j]=a[i];
a[i]=tmp;
j++;
}
}
}

int main()
{
int a[10]={1, 2, 0, 1, 0, 2, 1, 0, 0, 2},i,n=10;
cout<<"Before Shifting Values of Array are:\n";
for(i=0;i<n;i++)
cout<<a[i]<<", ";
cout<<endl;

shiftNumbers(a,n);
cout<<"\nAfter Shifting Values of Array are:\n";
for(i=0;i<n;i++)
cout<<a[i]<<", ";
cout<<endl;
}



No comments

Post your comments

Powered by Blogger.