Java Array Exercises: Sort a given binary array in linear times

Java Array: Exercise-56 with Solution

Write a Java program to sort a given binary array in linear times.

From Wikipedia,
Linear time: An algorithm is said to take linear time, or O(n) time, if its time complexity is O(n). Informally, this means that the running time increases at most linearly with the size of the input. More precisely, this means that there is a constant c such that the running time is at most cn for every input of size n. For example, a procedure that adds up all elements of a list requires time proportional to the length of the list, if the adding time is constant, or, at least, bounded by a constant.
Linear time is the best possible time complexity in situations where the algorithm has to sequentially read its entire input. Therefore, much research has been invested into discovering algorithms exhibiting linear time or, at least, nearly linear time. This research includes both software and hardware methods. There are several hardware technologies which exploit parallelism to provide this. An example is content-addressable memory. This concept of linear time is used in string matching algorithms such as the Boyer–Moore algorithm and Ukkonen's algorithm.

Input :
b_nums[] = { 0, 1, 1, 0, 1, 1, 0, 1, 0, 0 }
After sorting: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

Sample Solution:

Java Code:

import java.util.Arrays;

class solution

	public static void sort_binary_nums(int[] b_nums)
		int k = 0;

		for (int i = 0; i < b_nums.length; i++)
			if (b_nums[i] == 0) {
				b_nums[k++] = 0;

		for (int i = k; i < b_nums.length; i++) {
			b_nums[k++] = 1;

	public static void main (String[] args)
		int b_nums[] = { 0, 1, 1, 0, 1, 1, 0, 1, 0, 0 };
        System.out.println("Original array: "+Arrays.toString(b_nums)); 
		System.out.println("After sorting: "+Arrays.toString(b_nums));

Sample Output:

Original array: [0, 1, 1, 0, 1, 1, 0, 1, 0, 0]
After sorting: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]


Flowchart: Sort a given binary array in linear times

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to print all sub-arrays with 0 sum present in a given array of integers.
Next: Write a Java program to check if a sub-array is formed by consecutive integers from a given array of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter

Java: Tips of the Day


Counts the occurrences of a value in an array.

Use Arrays.stream().filter().count() to count total number of values that equals the specified value.

public static long countOccurrences(int[] numbers, int value) {
    return Arrays.stream(numbers)
            .filter(number -> number == value)

Ref: https://bit.ly/3kCAgLb