Saturday 25 July 2015

Reverse elements of array

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

It is very sample, suppose array has n elmenets,
Swap arr[0] with arr[n-1], arr[1] with arr[n-2] like this.

Step 1: int start=0, end=arr.length-1;

Step 2: while(start < end){
         swap(arr[start], arr[end]);
         start++; end--;
}

Once start reaches end, then we can stop this procedure.

Will apply for above example.

Step 1: Initial array like below.
Step 2: start=0, end=5; swap(arr[start], arr[end])
Step 3: start=1, end=4; swap(arr[start], arr[end])
Step 4: start=2, end=3; swap(arr[start], arr[end])

Find complete working application below.
import java.util.Objects;

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

  int start = 0, end = arr.length - 1;
  int temp;

  while (start < end) {
   temp = arr[start];
   arr[start] = arr[end];
   arr[end] = temp;
   start++;
   end--;
  }
 }
}


Following are the junit test cases for above application.

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

  ReverseArray.reverseArray(arr1);
  ReverseArray.reverseArray(arr2);
  ReverseArray.reverseArray(arr3);

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

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




No comments:

Post a Comment