Wednesday, February 16, 2011

Sorting Long Array which contains 0's and 1's by Traversing through the array only once


 class Sorting_Array_By_Traversing_Only_Once   
 {   
         public static void main(String[] args)   
         {   
                 int a[] = {0,1,0,1,0,0,0,1,1,1,1,0,0,0,1,0,1,1,0,1,0,1,0};   
                 int start=0;   
                 int end=a.length-1;   
                 while (start<end)   
                 {   
                         if (a[start]==0&&a[end]==0)   
                         {   
                                 start++;   
                         }   
                         else if (a[start]==1&&a[end]==0)   
                         {   
                                 a[start]=0;   
                                 a[end]=1;   
                                 start++;   
                                 end--;   
                         }   
                         else if (a[start]==1&&a[end]==1)   
                         {   
                                 end--;   
                         }   
                         else   
                         {   
                                 start++;   
                                 end--;   
                         }   
                 }   
                 for (int i=0; i<a.length; i++)   
                 {   
                         System.out.print(a[i]+" ");   
                 }   
         }   
 }  

No comments:

Post a Comment