Author: techfox9

Merge two sorted arrays in Java

Wednesday, October 9th, 2013 @ 7:34 pm

. . .

From: based on http://stackoverflow.com/questions/5958169/how-to-merge-two-sorted-arrays-into-a-sorted-array

[java]

public class m2a {

public static int[] merge(int[] a, int[] b) {

int[] ma = new int[a.length + b.length];
int ax = 0, bx = 0, mx = 0;
while (ax < a.length && bx < b.length) {
if (a[ax] < b[bx]) {
ma[mx++] = a[ax++];
}
else {
ma[mx++] = b[bx++];
}
}

while (ax < a.length) {
ma[mx++] = a[ax++];
}

while (bx < b.length) {
ma[mx++] = b[bx++];
}

return ma;
}

public static void main(String[] args) {
m2a om2a = new m2a();
int a[] = {1, 3, 5, 7};
int b[] = {3, 4, 6, 9};
int ma[] = om2a.merge(a, b);
for ( int mx = 0 ; mx < ma.length ; mx++ ) {
System.out.print(ma[mx] + ” “);
}
System.out.println();
}

}

[/java]

More compact, from same post, newer answer ..

[java]

public class m2a {

public static int[] merge(int[] aa, int[] ba) {

int[] ma = new int[aa.length + ba.length];
int ax = 0, bx = 0, mx = 0;

while (ax < aa.length && bx < ba.length) {
if (aa[ax] < ba[bx])
ma[mx++] = aa[ax++];
else
ma[mx++] = ba[bx++];
}

while (ax < aa.length)
ma[mx++] = aa[ax++];

while (bx < ba.length)
ma[mx++] = ba[bx++];

return ma;
}

public static void main(String[] args) {
m2a om2a = new m2a();
int a[] = {1, 3, 5, 7};
int b[] = {3, 4, 6, 9};
int ma[];

ma = om2a.merge(a, b);
for ( int mx = 0 ; mx < ma.length ; mx++ ) {
System.out.print(ma[mx] + ” “);
}
System.out.println();
}

}

[/java]

Algorithms, Java


 


Comments are closed.