java array program to sort list in binary of 0s and 1s

Posted by

The  below java program executes the java method – sortArrayElementsInBinaryFormat( ) to sort the received list into the Binary format of 0s and 1s in sequence.

Program Logic:

1. Pass the Array Element List to the method – sortArrayElementsInBinaryFormat( )

2. Traverse and identify the elements with 0 value

3. Move the elements with 0 value forward and elements with value 1 thereafter

4. Print the sorted binary array

Array Input :  { 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 }

Array Output: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

/*
 * Java Array Program to sort the received Array Binary Input of 0 and 1
 * identify the elements with 0 value
 * Move the elements with 0 value forward in the Array 
 * elements with 1 value to be placed after all 0s 
 * Input : { 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 }
 * Output: {0,0,0,0,0,1,1,1,1,1,1}
 */
package core.java.oracleappshelp.array;
import java.util.Arrays;
public class GenerateBinaryArray {
/*  Method - sortArrayElementsInBinaryFormat
 *  Java Method to sort the received list into the Binary format of 0 and 1 in sequence.
 */
		public static void sortArrayElementsInBinaryFormat(int[] arrayElements)
		{
			// identify the elements with 0 value
			int elementWithZeroValue = 0;
			for (int elementValue : arrayElements) {
				if (elementValue == 0) {
					elementWithZeroValue++;
				}
			}
			// move the elements with 0 value forward and elements with value 1 thereafter
			int elementLoop = 0;
			while (elementWithZeroValue-- != 0) {
				arrayElements[elementLoop++] = 0;
			}
			// fill all remaining elements by 1
			while (elementLoop < arrayElements.length) {
				arrayElements[elementLoop++] = 1;
			}
		}
		// Sort binary array in linear time
		public static void main (String[] args)
		{
			int[] arrayElementList = { 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0 };
			sortArrayElementsInBinaryFormat(arrayElementList);
			// print the sorted binary array
			System.out.println(Arrays.toString(arrayElementList));
		}
}
Java Array Program Output: 
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]