Merge Two Sorted Arrays

This Java program merges two sorted arrays into a single sorted array. The program assumes that the input arrays are already sorted in non-decreasing order. The output will be a new array containing all elements from the two input arrays, sorted in non-decreasing order.

Program Structure

  • Main Class: The main class contains the logic to merge two sorted arrays.
  • Merge Function: A static function to perform the merging of two sorted arrays.

Java Code

/**
 * This program merges two sorted arrays into a single sorted array.
 */
public class MergeSortedArrays {

    /**
     * Merges two sorted arrays into a single sorted array.
     * @param array1 The first sorted array.
     * @param array2 The second sorted array.
     * @return A new sorted array containing all elements from array1 and array2.
     */
    public static int[] mergeSortedArrays(int[] array1, int[] array2) {
        int[] mergedArray = new int[array1.length + array2.length];
        int i = 0, j = 0, k = 0;

        // Merge arrays while there are elements in both arrays
        while (i < array1.length && j < array2.length) {
            if (array1[i] <= array2[j]) {
                mergedArray[k++] = array1[i++];
            } else {
                mergedArray[k++] = array2[j++];
            }
        }

        // Copy remaining elements of array1, if any
        while (i < array1.length) {
            mergedArray[k++] = array1[i++];
        }

        // Copy remaining elements of array2, if any
        while (j < array2.length) {
            mergedArray[k++] = array2[j++];
        }

        return mergedArray;
    }

    public static void main(String[] args) {
        int[] array1 = {1, 3, 5, 7};
        int[] array2 = {2, 4, 6, 8};

        int[] mergedArray = mergeSortedArrays(array1, array2);

        System.out.print("Merged Array: ");
        for (int num : mergedArray) {
            System.out.print(num + " ");
        }
    }
}

Explanation

The program consists of the following parts:

  1. mergeSortedArrays Function: This function takes two sorted arrays as input and returns a new array that is the result of merging the two input arrays. It uses three pointers:
    • i: Tracks the current position in the first array.
    • j: Tracks the current position in the second array.
    • k: Tracks the current position in the merged array.

    The function compares elements from both arrays and inserts the smaller element into the merged array. It continues this process until all elements from one of the arrays have been added to the merged array. It then adds any remaining elements from the other array.

  2. Main Method: The main method initializes two sorted arrays, calls the mergeSortedArrays function, and prints the merged array to the console.

Output

When the program is executed, it will output the merged array:

Merged Array: 1 2 3 4 5 6 7 8

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)