Wednesday 8 August 2012

Without using extra space place all zeroes to left and 1's to right from an array of Zero's and 1's as below 011001 ans. 000111


#include<iostream.h>
#include<conio.h>
void main()
{
      clrscr();
      int a[]={0,1,1,0,0,1};
      int n=sizeof(a)/sizeof(int);
      int i=0,j=n-1;
      while(i<j)
      {
            if(a[i]==0)
                  i++;
            if(a[j]==1)
                  j--;
            if(a[i]==1 && a[j]==0)
            {
                  a[i]=0;
                  a[j]=1;
                  i++;
                  j--;
            }
      }
      for(i=0;i<n;i++)
            cout<<" "<<a[i];
      getch();
}

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Yes you can do it by counting number of 0's and 1's as well given, array can be traversed twice.
    But if there is a restriction that array can be traversed only once in that case the counting method won't fit.

    ReplyDelete