Thursday 30 July 2015

Move elements in even position to left and odd positions to right (Maintain order)

Suppose elements are {1, 2, 3, 4, 5, 6, 7, 8, 9}

Step 1: start=1, end = arr.length-1;
If array length is even length end = arr.length-2.

Step 2: Swap adjacent elements from start to end. Increment start by 1 and decrement end by 1. Repeat this procedure until start < end.

{1, 2, 3, 4, 5, 6, 7, 8} start=1, end=6
{1, 3, 2, 5, 4, 7, 6, 8} start=2, end=5
{1, 3, 5, 2, 7, 4, 6, 8} start=3, end=4
{1, 3, 5, 7, 2, 4, 6, 8} start=4 end=3.
Following is the working example.
import java.util.Objects;

public class MoveElements {

 public static void moveElements(int arr[]) {
  Objects.nonNull(arr);
  int length = arr.length;
  int start = 1, end = arr.length - 1;

  if (length % 2 == 0)
   end = arr.length - 2;

  while (start < end) {
   for (int i = start; i < end; i += 2) {
    int temp = arr[i];
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
   }
   start++;
   end--;
  }

 }
}


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

import java.util.Arrays;

import org.junit.Test;

public class MoveElementsTest {
 @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, 3, 5, 2, 4 };
  int expected6[] = { 1, 3, 5, 2, 4, 6 };
  int expected7[] = { 1, 3, 5, 7, 2, 4, 6 };
  int expected8[] = { 1, 3, 5, 7, 2, 4, 6, 8 };

  MoveElements.moveElements(arr1);
  MoveElements.moveElements(arr2);
  MoveElements.moveElements(arr3);
  MoveElements.moveElements(arr4);
  MoveElements.moveElements(arr5);
  MoveElements.moveElements(arr6);
  MoveElements.moveElements(arr7);
  MoveElements.moveElements(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