Breaking
Array

Merge Sorted using Array

Write a program to sort the two sorted array of numbers using merge sort.

Source Code

```package com.dsacode.DataStructre.array;

import java.util.Arrays;

public class MergeSort {
public int[] merge(int[] A, int[] B ) {
int[] C = new int[A.length+B.length];
int i, j, k, m, n;
i = 0;
j = 0;
k = 0;
m = A.length;
n = B.length;
while (i < m && j < n) {
if (A[i] <= B[j]) {
C[k] = A[i];
i++;
} else {
C[k] = B[j];
j++;
}
k++;
}
if (i < m) {
for (int p = i; p < m; p++) {
C[k] = A[p];
k++;
}
} else {
for (int p = j; p < n; p++) {
C[k] = B[p];
k++;
}
}

return C;
}
public static void main(String[] args) {

int[]a = {1, 2, 3};
int[]b = {4, 5, 6};

System.out.println("Array one items:" + Arrays.toString(a));
System.out.println("Array two items:" + Arrays.toString(b));
MergeSort m = new MergeSort();
int[] res = m.merge(a, b);

System.out.println("After Merge two arrays and sorted array:"+Arrays.toString(res));

}

}```

Output

```Array one items:[1, 2, 3]
Array two items:[4, 5, 6]
After Merge two arrays and sorted array:[1, 2, 3, 4, 5, 6]```