Merge Sorted Arrays in Java: Explanation & Practice

Merge two sorted arrays into one sorted array

Problem summary

Write a program that merges two sorted arrays into a single sorted array.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr1 = {1, 3, 5, 7};
        int[] arr2 = {2, 4, 6, 8}; // Test case 1
        
        // Merge into sorted result
        // Print space-separated
    }
}

Expected output and test cases

  • Merge two arrays
    1 2 3 4 5 6 7 8
  • Merge [1,3,5] and [2,4]
    1 2 3 4 5
  • Merge with duplicates
    1 1 2 2 3 3

Hints

  1. Use two pointers, one for each array
  2. Compare and pick smaller element
  3. Don't forget remaining elements

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler