Tuesday 28 July 2015

Reverse first n elements of array

Write a program to reverse first n elements of an array.
If array has elements {1, 2, 3, 4, 5, 6}, then reverse first 3 elements of array changes like {3, 2, 1, 4, 5, 6}.

It is very sample, suppose we need to reverse n elmenets,
Swap arr[0] with arr[n-1], arr[1] with arr[n-2] like this.

Step 1: int start=0, end=n-1;

Step 2: while(start < end){
         swap(arr[start], arr[end]);
         start++; end--;
}
Once start reaches end, we can stop this procedure.
import java.util.Objects;

public class ReverseArray {
 public static void reverseArray(int arr[], int noOfElements) {
  Objects.nonNull(arr);
  if (arr.length == 1 || noOfElements > arr.length || noOfElements < 2)
   return;

  int start = 0, end = noOfElements - 1;
  int temp;

  while (start < end) {
   temp = arr[start];
   arr[start] = arr[end];
   arr[end] = temp;
   start++;
   end--;
  }
 }
}
Following are the junit test cases.

import static org.junit.Assert.assertTrue;

import java.util.Arrays;

import org.junit.Test;

public class ReverseArrayTest {
 @Test
 public void test1() {
  int arr1[] = { 1, 2, 3, 4, 5, 6 };
  int expected1[] = { 6, 5, 4, 3, 2, 1 };

  int arr2[] = { 1, 2, 3, 4, 5, 6, 7 };
  int expected2[] = { 7, 6, 5, 4, 3, 2, 1 };

  int arr3[] = { 1 };
  int expected3[] = { 1 };

  int arr4[] = { 1, 2, 3, 4, 5, 6 };
  int expected4[] = { 3, 2, 1, 4, 5, 6 };

  int arr5[] = { 1, 2, 3, 4, 5, 6, 7 };
  int expected5[] = { 2, 1, 3, 4, 5, 6, 7 };

  int arr6[] = { 1 };
  int expected6[] = { 1 };

  ReverseArray.reverseArray(arr1, arr1.length);
  ReverseArray.reverseArray(arr2, arr2.length);
  ReverseArray.reverseArray(arr3, arr3.length);
  ReverseArray.reverseArray(arr4, 3);
  ReverseArray.reverseArray(arr5, 2);
  ReverseArray.reverseArray(arr6, 1);

  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));

 }

 @Test(expected = NullPointerException.class)
 public void test2() {
  ReverseArray.reverseArray(null, 1);
 }

 public void test3() {
  int arr1[] = { 1, 2, 3, 4, 5, 6 };
  int expected1[] = { 6, 5, 4, 3, 2, 1 };

  ReverseArray.reverseArray(arr1, 7);

  assertTrue(Arrays.equals(arr1, expected1));
 }
}



No comments:

Post a Comment