An array is filled with only 0's and 1's randomly.
Write a program so that all the 0's are on one side and all the 1's are on other side of the array.
The sample program is as follows:
package com.sample;
/*
Write a program to separate 0's and 1's from an array where all the numbers are only 1 or 0.
*/
public class ArrayTest {
public static void main(String[] args) {
int[] ar = { 0, 0, 1, 0, 0, 1, 1, 0, 0, 1 };
System.out.println("The given array before ->");
for (int i = 0; i < ar.length; i++) {
System.out.print(ar[i] + " ");
}
sort(ar);
System.out.println("\nThe given array after arrangement->");
for (int i = 0; i < ar.length; i++) {
System.out.print(ar[i] + " ");
}
}
private static void sort(int[] ar) {
int i = 0;
int j = ar.length - 1;
int temp;
while (i < j) {
if (ar[i] == 1) {
i++;
}
if (ar[j] == 0) {
j--;
}
if (ar[i] == 0) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
}
}
The output of the above program is as below:
The given array before ->
0 0 1 0 0 1 1 0 0 1
The given array after arrangement->
1 1 1 1 0 0 0 0 0 0
Comments
Post a Comment