Tuesday 18 August 2015

Merge two sorted arrays


Suppose there are two sorted arrays arr1 = {1, 3, 5, 7, 11, 13}, arr2 = {2, 4, 6}. Final resulted array after merging is arr3 = {1, 2, 3, 4, 5, 6, 7, 11, 13}
import java.util.Objects;

public class MergeArrays {

 public static int[] mergeArrays(int[] arr1, int[] arr2) {
  Objects.nonNull(arr1);
  Objects.nonNull(arr2);

  int length1 = arr1.length;
  int length2 = arr2.length;
  int[] result = new int[length1 + length2];

  int i = 0, j = 0, count = 0;

  while (i < length1 && j < length2) {
   if (arr1[i] > arr2[j])
    result[count++] = arr2[j++];
   else
    result[count++] = arr1[i++];
  }

  if (i == length1) {
   while (j < length2) {
    result[count++] = arr2[j++];
   }
  }

  if (j == length2) {
   while (i < length1) {
    result[count++] = arr1[i++];
   }
  }

  return result;
 }
}


Following is the junit test case for above program.
import static org.junit.Assert.assertTrue;

import java.util.Arrays;

import org.junit.Test;

public class MergeArraysTest {
 @Test
 public void test1() {
  int[] arr1 = { 1, 3, 5, 7, 11, 13 }, arr2 = { 2, 4, 6 }, arr3 = { -10,
    -14, 100, 103 };

  int[] result1 = MergeArrays.mergeArrays(arr1, arr2);
  int[] result2 = MergeArrays.mergeArrays(arr1, arr3);
  int[] result3 = MergeArrays.mergeArrays(arr2, arr3);

  assertTrue(Arrays.equals(result1, new int[] { 1, 2, 3, 4, 5, 6, 7, 11,
    13 }));
  assertTrue(Arrays.equals(result2, new int[] { -10, -14, 1, 3, 5, 7, 11,
    13, 100, 103 }));
  assertTrue(Arrays.equals(result3, new int[] { -10, -14, 2, 4, 6, 100,
    103 }));

 }
}



No comments:

Post a Comment