Skip to content

Instantly share code, notes, and snippets.

@dkohlsdorf
Last active March 13, 2019 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkohlsdorf/92410ff95fcc5c0bfdd9 to your computer and use it in GitHub Desktop.
Save dkohlsdorf/92410ff95fcc5c0bfdd9 to your computer and use it in GitHub Desktop.
Merge As In Mergesort
import java.util.Arrays;
/**
* Merge as in MergeSort
*
* @author Daniel Kohlsdorf
*/
public class Merge {
public static int[] merge(int x[], int y[]) {
int merged[] = new int[x.length + y.length];
int i = 0;
int j = 0;
int pos;
for (pos = 0; pos < x.length + y.length; pos++) {
if (i < x.length && j < y.length) {
if (x[i] < y[j]) {
merged[pos] = x[i];
i++;
} else {
merged[pos] = y[j];
j++;
}
}
}
pos -= 1;
for(; i < x.length; i++, pos++) {
merged[pos] = x[i];
}
for(; j < y.length; j++, pos++) {
merged[pos] = y[j];
}
return merged;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(merge(new int[] { 3, 4, 5, 23 },
new int[] { 1, 2, 10 })));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment