Skip to main content

Sort binary array using one traversal in java

Java program for Sort binary array using one traversal. Here problem description and explanation.

  Java program for
  Sort a given binary array
public class Sorting
	// Sort the array elements which are contain 0 and 1s
	public void sort(int arr[], int n)
		// This is indicate starting index of zero element
		int start = 0;
		// Iterating the loop from 0 to n.size
		for (int i = 0; i < n; ++i)
			// Check zero 
			if (arr[i] == 0)
				// Set zero at front
				arr[start] = 0;
				if (start != i)
					// When current index and start are not same
					arr[i] = 1;
				// Change index value
	// Display array element values
	public void dispay(int[] arr, int n)
		for (int i = 0; i < n; ++i)
			// print element value
			System.out.print("  " + arr[i]);
	public static void main(String[] args)
		Sorting task = new Sorting();
		// Define the array of binary elements
		int[] arr = {
			0 , 1 , 1 , 0 , 1 , 0 , 1 , 1 , 0 , 1
		// Get the size of array
		int n = arr.length;
		System.out.println("  Before Sort :");
		task.dispay(arr, n);
		// Test
		task.sort(arr, n);
		System.out.println("  After Sort :");
		task.dispay(arr, n);


  Before Sort :
  0  1  1  0  1  0  1  1  0  1
  After Sort :
  0  0  0  0  1  1  1  1  1  1

This is a Java program that sorts an array of binary elements (0's and 1's) such that all the 0's appear before all the 1's.

The program defines a class Sorting with two methods: sort() and display().

The sort() method takes two arguments, an integer array arr and an integer n, which is the size of the array. It sorts the array by moving all the 0's to the beginning of the array, and all the 1's to the end. It does this by maintaining an index start that indicates the starting index of the 0's. It then iterates through the array, and when it encounters a 0, it moves it to the beginning of the array by swapping it with the element at index start. If the current index i is not equal to start, it swaps the element at index i with a 1. Finally, it increments start by 1.

The display() method takes two arguments, an integer array arr and an integer n, and prints the elements of the array to the console.

The main() method creates an instance of the Sorting class, initializes an integer array arr with some binary elements, and prints the array before and after sorting using the display() method. It then calls the sort() method to sort the array.

Overall, this program is a simple implementation of a sorting algorithm that sorts an array of binary elements in linear time.


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment