Wednesday 29 July 2015

Move elements in even position to left and odd positions to right

Suppose array has n elements, move all the elements in even positions to left and odd positions to right (Order doesn't matter).
import java.util.Objects;

public class PositionSwap {

 public static void positionSwap(int arr[]) {
  Objects.nonNull(arr);
  if (arr.length == 1)
   return;

  int even = 1;
  int odd = arr.length - 1;

  if (odd % 2 != 0)
   odd = odd - 1;

  for (int i = even; i < odd; i++) {
   int temp = arr[even];
   arr[even] = arr[odd];
   arr[odd] = temp;

   even += 2;
   odd -= 2;
  }
 }
}


Following is the junit test case for above program.
import static org.junit.Assert.*;

import java.util.Arrays;

import org.junit.Test;

public class PositionSwapTest {

 @Test
 public void test1() {
  int arr1[] = { 1 };
  int arr2[] = { 1, 2 };
  int arr3[] = { 1, 2, 3 };
  int arr4[] = { 1, 2, 3, 4 };
  int arr5[] = { 1, 2, 3, 4, 5 };
  int arr6[] = { 1, 2, 3, 4, 5, 6 };
  int arr7[] = { 1, 2, 3, 4, 5, 6, 7 };
  int arr8[] = { 1, 2, 3, 4, 5, 6, 7, 8 };

  int expected1[] = { 1 };
  int expected2[] = { 1, 2 };
  int expected3[] = { 1, 3, 2 };
  int expected4[] = { 1, 3, 2, 4 };
  int expected5[] = { 1, 5, 3, 4, 2 };
  int expected6[] = { 1, 5, 3, 4, 2, 6 };
  int expected7[] = { 1, 7, 3, 5, 4, 6, 2 };
  int expected8[] = { 1, 7, 3, 5, 4, 6, 2, 8 };

  PositionSwap.positionSwap(arr1);
  PositionSwap.positionSwap(arr2);
  PositionSwap.positionSwap(arr3);
  PositionSwap.positionSwap(arr4);
  PositionSwap.positionSwap(arr5);
  PositionSwap.positionSwap(arr6);
  PositionSwap.positionSwap(arr7);
  PositionSwap.positionSwap(arr8);

  assertTrue(Arrays.equals(arr1, expected1));
  assertTrue(Arrays.equals(arr2, expected2));
  assertTrue(Arrays.equals(arr3, expected3));
  assertTrue(Arrays.equals(arr4, expected4));
  assertTrue(Arrays.equals(arr5, expected5));
  assertTrue(Arrays.equals(arr6, expected6));
  assertTrue(Arrays.equals(arr7, expected7));
  assertTrue(Arrays.equals(arr8, expected8));

 }

}



No comments:

Post a Comment