SIGN UP MEMBER LOGIN:    
Blog

Efficient Algorithm: Separate all 1s and 0s in a given array of 1s and 0s.

Posted by Suresh Paldia Blogs | Algorithms in C# Nov 25, 2010
Consider an array of only 1s and 0s. Write an algorithm that will separate all 1s and all 0s. Try to do it in one parse of array.

Consider an array of only 1s and 0s. Write an algorithm that will separate all 1s and all 0s.

Efficeint Way: Try to do it in one parse of array.

  1. Have two indexes pointing to two ends of array, say i and j.
  2. Approach towards each other with a check condition that they dont cross each other.
  3. Each iteration of while loop, swap the numbers pointed by two indexes when num[i] index number is not equal to 1.

Here is the running code…


void sort()
{
     int a[]={1,0,0,0,1,1,0,1,0,1,0,0,1,0};
     int j=13;
     int i=0;
     int temp;
 
     while(j>i)
     {
          if(a[i]==1)
                 i++;
          if(a[j]==0)
                 j--;
          if(a[i]==0)
         {
                 temp=a[i];
                a[i]=a[j];
                a[j]=temp;
         }
     }

     for(i=0;i<14;i++)
             Console.Write(a[i]+", ");
}

Output: 1,1,1,1,1,1,0,0,0,0,0,0,0

Happy Learning...
share this blog :
post comment
 

What you have written above is a pass of Quick Sort.. This is just one of the solution.. If you see the time taken by your Algorithm is O(n)..with O(n) being the time complexity, the easiest solution is to count the zeros (or ones).. in first pass just count the number of 1's (say k) and in the second pass put (n-k) 0's and k 1's..

Posted by Kamal Rawat Aug 01, 2011