Skip to main content

Java Problem 04 | Median of Two Sorted arrays in Java

Hey everyone! In this quick coding tutorial, I walk through a simple Java program that finds the median of two arrays. We manually merge two arrays, sort them, and then calculate the median step by step.

What we cover in this video:

  • Creating two sample arrays and merging them without using built-in merge methods
  • Manual array copying using loops
  • Sorting the combined array with Arrays.sort()
  • Determining if the array length is odd or even
  • Calculating the median based on the middle element(s)
  • Printing the final result

Code Example Used:

We work with two arrays: {1, 3, 2} and {5, 4, 6}, merge them, sort to {1, 2, 3, 4, 5, 6}, and compute the median.

Why I Made This:

I often see median problems in coding interviews, so I wanted to break down the logic clearly without relying on complex libraries. This is a beginner-friendly approach to understanding what happens under the hood.

Got Questions or Suggestions?

Drop them in the comments — I read them all! If you found this helpful, feel free to like the video and subscribe for more Java and problem-solving content.



import java.util.Arrays;

public class MedianFinder {
	public static void main(String[] args) {
		// Define two input arrays
		int[] num1 = new int[] {1, 3, 2};
		int[] num2 = new int[] {5, 4, 6};
		
		// Create an array to hold merged elements from both arrays
		int[] mergedArray = new int[num1.length + num2.length];
		
		// Copy elements from num1 into the beginning of mergedArray
		for (int i = 0; i < num1.length; i++) {
			mergedArray[i] = num1[i];
		}
		
		// Copy elements from num2 after the elements from num1
		for (int i = 0; i < num2.length; i++) {
			mergedArray[num1.length + i] = num2[i];
		}
		
		// Sort the merged array in ascending order
		Arrays.sort(mergedArray);
		
		// Check if the merged array has an even number of elements
		if (mergedArray.length % 2 == 0) {
			// For even length: median is average of two middle elements
			int mid = mergedArray.length / 2;            // Index of second middle element
			int midL = mergedArray[mid - 1];            // First middle element
			int midR = mergedArray[mid];                // Second middle element
			double ans = (double) (midL + midR) / 2;    // Calculate average as double
			System.out.println(ans);                    // Print median
		} else {
			// For odd length: median is the middle element
			System.out.println(mergedArray[mergedArray.length / 2]);
		}
	}
}

Comments

Popular posts from this blog

How to fix MOV files not playing on Windows 10 or 11

How to TEST KEYBOARDS on PC or Laptop

Apple CONFIRMS iPhone 17 Pro Max Camera Noise Bug - Fix Coming?