Wednesday, 29 July 2015

Sort array of 0’s and 1’s

Array has 0’s and 1’s sort array like that all  0’s should come left and all 1’s should go right side.
import java.util.Objects;

public class SortZerosOnes {

 public static void sortArray(int arr[]) {
  Objects.nonNull(arr);
  if (arr.length < 2)
   return;

  int counter2 = arr.length - 1;

  for (int i = 0; i < counter2; i++) {
   if (arr[i] != 1 && arr[i] != 0)
    throw new IllegalArgumentException(
      "Array contains values other than 0, 1 : " + arr[i]);

   if (arr[i] == 1) {
    int temp = arr[i];
    arr[i] = arr[counter2];
    arr[counter2] = temp;
    i--;
    counter2--;
   }
  }
 }
}


Following is the junit test case for above class.
import static org.junit.Assert.assertTrue;

import java.util.Arrays;

import org.junit.Test;

public class SortZerosOnesTest {
 @Test
 public void test1() {
  int arr1[] = { 0, 1, 0, 1, 0, 1 };
  int arr2[] = { 0, 0, 1, 0, 1, 0, 1, 0, 0, 1 };
  int arr3[] = { 1, 0 };

  int expected1[] = { 0, 0, 0, 1, 1, 1 };
  int expected2[] = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 };
  int expected3[] = { 0, 1 };

  SortZerosOnes.sortArray(arr1);
  SortZerosOnes.sortArray(arr2);
  SortZerosOnes.sortArray(arr3);

  assertTrue(Arrays.equals(arr1, expected1));
  assertTrue(Arrays.equals(arr2, expected2));
  assertTrue(Arrays.equals(arr3, expected3));
 }
}



No comments:

Post a Comment