Array

Merge Sorted using Array

Pinterest LinkedIn Tumblr

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

Algorithm Explanation

Initialize the two sorted array and pass the array to the utility function.
Create the new array with combination of array1 and array2 size. Initialize three loop variable for iterate the three arrays.
Sort the array items using merge sort.
Return the third sorted array and print the values.

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]

Write A Comment