Skip to content
Advertisement

Sorting in java for array only containing 0 and 1

How to sort array

int[] A = {0,1,1,0,1,0,1,1,0} 

Advertisement

Answer

use any sorting algorithm to do it. For beginner use bubble sort (easy to understand)
Refer Wiki

public static void bubble_srt( int a[], int n ){
  int i, j,t=0;
  for(i = 0; i < n; i++){
    for(j = 1; j < (n-i); j++){
      if(a[j-1] > a[j]){
        t = a[j-1];
        a[j-1]=a[j];
        a[j]=t;
      }
    }
  }
}

EDITED
As @Pradeep Said: You may definitely use Array.sort()

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement