Tuesday, 11 February 2020

Java: Reverse an integer array

Approach 1: Traversing array.
public static void reverse_approach1(int[] arr) {
 if (arr == null || arr.length < 2) {
  return;
 }

 int length = arr.length;
 for (int i = 0; i < length / 2; i++) {
  int temp = arr[i];
  arr[i] = arr[length - i - 1];
  arr[length - i - 1] = temp;
 }

}

Approach 2: Using IntStream.
public static int[] reverse_approach2(int[] arr) {
 if (arr == null || arr.length < 2) {
  return arr;
 }

 return IntStream.rangeClosed(1, arr.length).map(i -> arr[arr.length-i]).toArray();
}

IntArrayUtil.java
package com.smaple.app.utils;

import java.util.stream.IntStream;

public class IntArrayUtil {

 public static void reverse_approach1(int[] arr) {
  if (arr == null || arr.length < 2) {
   return;
  }

  int length = arr.length;
  for (int i = 0; i < length / 2; i++) {
   int temp = arr[i];
   arr[i] = arr[length - i - 1];
   arr[length - i - 1] = temp;
  }

 }
 
 public static int[] reverse_approach2(int[] arr) {
  if (arr == null || arr.length < 2) {
   return arr;
  }

  return IntStream.rangeClosed(1, arr.length).map(i -> arr[arr.length-i]).toArray();
 }
}

IntArrayUtilTest.java

package com.sample.app.utils;

import static org.junit.Assert.*;

import org.junit.Test;

import com.smaple.app.utils.IntArrayUtil;

public class IntArrayUtilTest {

 @Test
 public void reverse_approach1_null() {
  int[] arr = null;
  IntArrayUtil.reverse_approach1(arr);

  assertNull(arr);
 }

 @Test
 public void reverse_approach1_empty() {
  int[] arr = {};
  IntArrayUtil.reverse_approach1(arr);

  assertEquals(arr.length, 0);
 }

 @Test
 public void reverse_approach1_oneElement() {
  int[] arr = { 1 };
  IntArrayUtil.reverse_approach1(arr);

  assertArrayEquals(arr, new int[] { 1 });
 }

 @Test
 public void reverse_approach1_moreElement() {
  int[] arr = { 1, 3, 5, 7, 2, 4, 6, 8 };
  IntArrayUtil.reverse_approach1(arr);

  assertArrayEquals(arr, new int[] { 8, 6, 4, 2, 7, 5, 3, 1 });
 }

 @Test
 public void reverse_approach2_null() {
  int[] arr = null;
  int[] result = IntArrayUtil.reverse_approach2(arr);

  assertNull(result);
 }

 @Test
 public void reverse_approach2_empty() {
  int[] arr = {};
  int[] result = IntArrayUtil.reverse_approach2(arr);

  assertEquals(result.length, 0);
 }

 @Test
 public void reverse_approach2_oneElement() {
  int[] arr = { 1 };
  int[] result = IntArrayUtil.reverse_approach2(arr);

  assertArrayEquals(result, new int[] { 1 });
 }

 @Test
 public void reverse_approach2_moreElement() {
  int[] arr = { 1, 3, 5, 7, 2, 4, 6, 8 };
  int[] result = IntArrayUtil.reverse_approach2(arr);

  assertArrayEquals(result, new int[] { 8, 6, 4, 2, 7, 5, 3, 1 });
 }
}


You may like

No comments:

Post a Comment