Skip to main content

Posts

Showing posts from October, 2014

Write a program to separate the 0's and 1's in either sides of an array.

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--; } ...