Monday 23 May 2016

Reverse an array in subset of N.

Example:
input: Array = [1,2,3,4,5,6,7,8,9], N = 3

output: [3,2,1,6,5,4,9,8,7]


import java.util.Objects;

public class ArrayUtil {
 public static void reverseArray(int arr[], int k) {
  if (Objects.isNull(arr) || arr.length == 1 || k <= 1 || k > arr.length)
   return;

  int length = arr.length;
  int iter = length / k;
  int start, stop;

  for (int i = 0; i < iter; i++) {
   start = i * k;
   stop = ((i + 1) * k) - 1;
   reverse(arr, start, stop);
  }

  int rem = length % k;
  start = (length - rem);
  stop = length - 1;

  reverse(arr, start, stop);

 }

 private static void reverse(int arr[], int start, int stop) {
  while (start < stop) {
   swap(arr, start, stop);
   start++;
   stop--;
  }
 }

 private static void swap(int arr[], int start, int stop) {
  int temp = arr[start];
  arr[start] = arr[stop];
  arr[stop] = temp;
 }

}


import org.junit.Assert;
import org.junit.Test;

public class ArrayUtilTest {

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

  int arr8[] = {};
  int arr9[] = { 1 };
  int arr10[] = null;

  ArrayUtil.reverseArray(arr1, 0);
  ArrayUtil.reverseArray(arr2, 1);
  ArrayUtil.reverseArray(arr3, 2);
  ArrayUtil.reverseArray(arr4, 3);
  ArrayUtil.reverseArray(arr5, 4);
  ArrayUtil.reverseArray(arr6, 5);
  ArrayUtil.reverseArray(arr7, 6);
  ArrayUtil.reverseArray(arr8, 1);
  ArrayUtil.reverseArray(arr9, 1);
  ArrayUtil.reverseArray(arr10, 1);

  Assert.assertArrayEquals(arr1, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9,
    10, 11 });
  Assert.assertArrayEquals(arr2, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9,
    10, 11 });
  Assert.assertArrayEquals(arr3, new int[] { 2, 1, 4, 3, 6, 5, 8, 7, 10,
    9, 11 });
  Assert.assertArrayEquals(arr4, new int[] { 3, 2, 1, 6, 5, 4, 9, 8, 7,
    11, 10 });
  Assert.assertArrayEquals(arr5, new int[] { 4, 3, 2, 1, 8, 7, 6, 5, 11,
    10, 9 });
  Assert.assertArrayEquals(arr6, new int[] { 5, 4, 3, 2, 1, 10, 9, 8, 7,
    6, 11 });
  Assert.assertArrayEquals(arr7, new int[] { 6, 5, 4, 3, 2, 1, 11, 10, 9,
    8, 7 });

  Assert.assertArrayEquals(arr8, new int[] {});
  Assert.assertArrayEquals(arr9, new int[] { 1 });
  Assert.assertArrayEquals(arr10, null);
 }
}



No comments:

Post a Comment