Code to sort an array of 0's and 1's efficiently


package org.training.algo;

public class SortZeroAndOne {

      public static void main(String args[]) {
           
            int array[] = {0,1,1,1,0,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,0,0,0,0,1,0,1,0,1,1};
            int numberOfOnes = 0;
           
            for (int i = 0 ; i < array.length; i++)
            {
                  // adding all the elements in the array, the result would be the number of ones in the array
                   numberOfOnes += array[i];
            }
           
            // subtract the number of ones from the length of the array to get the number of zeros in the array
            int numberOfZeros = array.length - numberOfOnes;
           
            System.out.println("Length of Array: "+ array.length);
            System.out.println("Number of Zeros: "+ numberOfZeros);
            System.out.println("Number of Ones: "+ numberOfOnes);
           
            for ( int i = 0; i < array.length; i++)
            {
                  // one reached the number of zeros start filling the array with one's
                  if (i >= numberOfZeros)
                  {
                        array[i] = 1;
                  }
                  else
                        // fill the first half with zeros
                        array[i] = 0;
            }
           
            for ( int i = 0; i < array.length; i++)
            {
                  System.out.print(array[i]+",");
            }
      }
}

Output:
Length of Array: 30
Number of Zeros: 18
Number of Ones: 12
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,

No comments: