Wednesday 19 June 2019

Sort a binary array using one traversal in Java

     In the current post, we can discuss the binary sort i.e 0 and 1 in Java. Given a binary array contains 0 & 1 in unsorted order, the output should be in sorted but we have to traverse only once.

Example:-

Input , array - {0,1,1,0,0,0,1,0,1}
Output, array - {0,0,0,0,0,1,1,1,1}

Java code:-

SortBinaryArray.java

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