Java Program to Merge Two Sorted Arrays

Here is a java program to merge two sorted array sin one single array. In this java program, we have to merge two sorted arrays into third array such that third array is also sorted. The size of the third array will be more than or equal to the sum of size of both given arrays.

For Example,
First Array : 1 3 5 7 9 11
Second Array : 2 4 6 8 10
Output Array : 1 2 3 4 5 6 7 8 9 10 11

Java program to merge two sorted array

package com.tcc.java.programs;

import java.util.Scanner;

public class MergeSortedArray {

    public static void main(String[] args) {
        int fSize, sSize, i, j, k;
        int first[] = new int[100];
        int second[] = new int[100];
        int merged[] = new int[200];

        Scanner scanner = new Scanner(System.in);
        // Input First Array
        System.out.println("Enter Number of Elements 
           in First Array");
        fSize = scanner.nextInt();
        System.out.println("Enter " + fSize + " Numbers");
        for (i = 0; i < fSize; i++) {
            first[i] = scanner.nextInt();
        }

        // Input Second Array
        System.out.println("Enter Number to Elements in Second Array");
        sSize = scanner.nextInt();
        System.out.println("Enter " + sSize + " Numbers");
        for (i = 0; i < sSize; i++) {
            second[i] = scanner.nextInt();
        }

        // Merge two array
        i = j = k = 0;
        while (i < fSize && j < sSize) {
            if (first[i] <= second[j]) {
                merged[k++] = first[i++];
            } else {
                merged[k++] = second[j++];
            }
        }

        if (i == fSize) {
            while (j < sSize)
                merged[k++] = second[j++];
        }

        if (j == sSize) {
            while (i < fSize)
                merged[k++] = first[i++];
        }

        System.out.println("Merged Array");
        for (i = 0; i < k; i++) {
            System.out.print(merged[i] + " ");
        }
    }
}
Output
Enter Number of Elements in First Array
5
Enter 5 Numbers
1 3 5 7 9
Enter Number to Elements in Second Array
4
Enter 4 Numbers
2 4 6 8
Merged Array
1 2 3 4 5 6 7 8 9

Recommended Posts
Java Program to Find Sum of Elements of an Array
Java Program to Concatenate Two Strings
Java Program to Delete All Spaces from a String
Java Program to Search an Element in an Array using Linear Search
Java Program to Find Average of all Array Elements
Java Program to Insert an Element in Array at Given Position
Java Program to Find Largest and Smallest Number in an Array
Java Program to Find Duplicate Elements in an Array
C++ Program to Find Largest Element of an Array
All Java Programs