To sort the array having binary numbers i.e. 0 & 1 only
public class BinarySort {
public static void main(String[] args) {
long start = System.nanoTime();
byte[] array = {0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0};
byte temp = 0;
for(int i = 0; i < array.length; i++){
if(i == 0)
continue;
if(array[i-1] == 1 && array[i] == 0){
for(int j = i; j > 0; j--){
// Below if block makes the loop shorter & execute the code twice faster
if(array[j-1] == 0)
break;
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
for(int i = 0; i < array.length; i++){
// System.out.println(array[i]);
}
System.out.println(System.nanoTime() - start);
}
}
public static void main(String[] args) {
long start = System.nanoTime();
byte[] array = {0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0};
byte temp = 0;
for(int i = 0; i < array.length; i++){
if(i == 0)
continue;
if(array[i-1] == 1 && array[i] == 0){
for(int j = i; j > 0; j--){
// Below if block makes the loop shorter & execute the code twice faster
if(array[j-1] == 0)
break;
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
for(int i = 0; i < array.length; i++){
// System.out.println(array[i]);
}
System.out.println(System.nanoTime() - start);
}
}