D3^!L
BAN USERAn easier approach may be to search for 0's from right and store it in a location say pos0
and 1's from left and store it in a location say pos1
Then swap them.
Continue this till the pos1<pos0
complexity : O(n)
Here is the code :
#include<stdio.h>
main()
{
int n,i,pos0,pos1;
printf("Enter size of array : ");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
pos0=n-1,pos1=0;
while(pos1<pos0)
{
if(a[pos1]==1 && a[pos0]==0)
a[pos1++]=0,a[pos0--]=1;
else if(a[pos1]==1)
pos0--;
else if(a[pos0]==0)
pos1++;
else
pos0--,pos1++;
}
printf("\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
}
Here is the c Code for above program
It forst looks for the starting point of second array
and then sorts it
- D3^!L June 08, 2013