Merge two sorted arrays in Java
Oct 09, 2013 in Algorithms, Java
. . .
From: based on http://stackoverflow.com/questions/5958169/how-to-merge-two-sorted-arrays-into-a-sorted-array
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(); } }
More compact, from same post, newer answer ..
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(); } }