In this post, we will discuss how to sort a binary array (containing only
0s and 1s) in Java. Given an unsorted binary array, the goal is to sort it by placing all 0s before all 1s while traversing the array only once.Example:
Input:
{0, 1, 1, 0, 0, 0, 1, 0, 1}
Output:
{0, 0, 0, 0, 0, 1, 1, 1, 1}
Java Program:
SortBinaryArray.java
Output:- 0 0 0 1 1 1 1
Related Posts:-
1) Java Program for Bubble Sort in Ascending and Descending order
2) Java Program to implement Selection Sort
3) Implementation of merge sort in Java
4) Java Object sorting example (Comparable and Comparable)
5) Difference between Comparable and Comparator Interface in Java
6) Java Program to Sort ArrayList of Custom Objects By Property using Comparator interface
7) Java program to find second largest number in an array
package com.practice;
public class SortBinaryArray {
public static void main(String[] args) {
int arr[] = {1, 0, 1, 0, 0, 1, 1};
SortBinaryArray sort = new SortBinaryArray();
sort.sortBinaryArray(arr);
for (int i =0; i<arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
private void sortBinaryArray(int arr[]) {
int length = arr.length;
int j = -1;
for (int i = 0; i < length; i++) {
if (arr[i] < 1) {
j++;
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
Output:- 0 0 0 1 1 1 1
Related Posts:-
1) Java Program for Bubble Sort in Ascending and Descending order
2) Java Program to implement Selection Sort
3) Implementation of merge sort in Java
4) Java Object sorting example (Comparable and Comparable)
5) Difference between Comparable and Comparator Interface in Java
6) Java Program to Sort ArrayList of Custom Objects By Property using Comparator interface
7) Java program to find second largest number in an array
No comments:
Post a Comment