Last active
March 13, 2019 20:59
-
-
Save dkohlsdorf/92410ff95fcc5c0bfdd9 to your computer and use it in GitHub Desktop.
Merge As In Mergesort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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