Program to Sort Binary array(Array of 0 and 1 only) in java


In this core java programming tutorial we will Write a Program to Sort Binary array(Array of 0 and 1 only) in java.



Example 1 in java >
Binary array before sorting : 10100101
Binary array after sorting  : 00001111


Example 2 in java >
Binary array before sorting : 101101010
Binary array after sorting  : 000011111

Example/ Full Program/SourceCode to Sort Binary array(Array of 0 and 1 only) in java >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class SortBinaryArrayExample {
   public static void main(String[] args) {
          int ar[] = { 1, 0, 1, 0, 0, 1, 0, 1 };
          System.out.print("Binary array before sorting : ");
          for (int n : ar)
                 System.out.print(n);
         
          //i will start from 0.
          //j will start from end.
          int i = 0, j = ar.length - 1;
         
          //We might face 4 conditions.
          while (i < j) {
                 //condition 1 - when a[i] is 1 and a[j] is 0
                 if (ar[i] > ar[j]) {
                       ar[i] = 0;
                       ar[j] = 1;
                       i++;
                       j--;
                 }
                 //condition 2 - when a[i] is 0 and a[j] is 0
                 else if (ar[i] == 0 && ar[j] == 0) {
                       i++;
                 }
                 //condition 3 - when a[i] is 1 and a[j] is 1
                 else if (ar[i] == 1 && ar[j] == 1) {
                       j--;
                 }
                 //condition 4 - when a[i] is 0 and a[j] is 1
                 else if (ar[i] < ar[j]) {
                       i++;
                       j--;
                 }
          }
          System.out.print("\nBinary array after sorting  : ");
          for (int n : ar)
                 System.out.print(n);
   }
}
/* Output
Binary array before sorting : 10100101
Binary array after sorting  : 00001111
*/


So in this core java programming tutorial we wrote a Program to Sort Binary array(Array of 0 and 1 only) in java.


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.





RELATED LINKS>






No comments:

Post a Comment