Tuesday 28 July 2015

Reverse array using recursion

Reverse an integer array using recursion.
import java.util.Objects;

public class ReverseArrayRecursion {

 public static void reverseArray(int arr[]) {
  Objects.nonNull(arr);

  reverse(arr, 0, arr.length - 1);
 }

 private static void reverse(int arr[], int start, int end) {
  if (start > end)
   return;

  int temp = arr[start];
  arr[start] = arr[end];
  arr[end] = temp;

  reverse(arr, ++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 ReverseArrayRecursionTest {
 @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 };

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

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



No comments:

Post a Comment