Tuesday 29 May 2018

Java Program to sort Binary Array



Sample Program:-


public class SampleProgram {  
      public static void main(String[] args) {  
           int ar[] = { 1, 0, 1, 1, 0, 1, 0, 1 };  
           System.out.print("Before sorting : ");  
           for (int n : ar)  
                System.out.print(n);  
           int i = 0, j = ar.length - 1;  
           while (i < j) {  
                if (ar[i] > ar[j]) {  
                     ar[i] = 0;  
                     ar[j] = 1;  
                     i++;  
                     j--;  
                }  
                else if (ar[i] == 0 && ar[j] == 0) {  
                     i++;  
                }  
                else if (ar[i] == 1 && ar[j] == 1) {  
                     j--;  
                }  
                else if (ar[i] < ar[j]) {  
                     i++;  
                     j--;  
                }  
           }  
           System.out.print("\nAfter sorting : ");  
           for (int n : ar)  
                System.out.print(n);  
      }  
 }  


Output:-


Before sorting : 10110101  
 After sorting : 00011111  

Enjoy Coding.

No comments:

Post a Comment