Skip to content

Instantly share code, notes, and snippets.

@vijayparikh
Last active February 16, 2018 23:01
Show Gist options
  • Save vijayparikh/75113575bfc8fb850b6f988a9f1f0cb9 to your computer and use it in GitHub Desktop.
Save vijayparikh/75113575bfc8fb850b6f988a9f1f0cb9 to your computer and use it in GitHub Desktop.
Merge two sorted arrays of different sizes efficiently
import java.io.*;
import java.util.*;
import java.text.*;
public class ArrayMerge {
public static int[] merge(int[] A, int[] B) {
int i, j, k, m, n;
i = 0;
j = 0;
k = 0;
m = A.length;
n = B.length;
int result[] = new int[A.length + B.length];
while (i < m && j < n) {
if (A[i] <= B[j]) {
result[k] = A[i];
i++;
} else {
result[k] = B[j];
j++;
}
k++;
}
if (i < m) {
for (int p = i; p < m; p++) {
result[k] = A[p];
k++;
}
} else {
for (int p = j; p < n; p++) {
result[k] = B[p];
k++;
}
}
return result;
}
public static int[] merge(int[] ...arrays)
{
int[] runningArray = arrays[0] ;
for (int i=1; i<arrays.length; i++)
{
runningArray = merge(runningArray, arrays[i]) ;
}
return runningArray ;
}
public static void main(String[] args) {
int[] Array1 = {1, 3, 4};
int[] Array2 = {2, 5, 6, 7, 8};
int[] Array3 = {9,10,11,12} ;
int result[] = merge(Array1, Array2);
System.out.println(Arrays.toString(result));
int result2[] = merge(Array1, Array2, Array3) ;
System.out.println(Arrays.toString(result2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment