Question

I have the following code:

public final class MedianOfTwoSortedArrays {  
    private MedianOfTwoSortedArrays() {}

    private static boolean isMedian (int[] a1, int[] a2, int pos) {
        if (pos == 0 || pos == (a1.length - 1)) return true;
        return (a1[pos] >= a2[pos]) && (a1[pos] <= a2[pos + 1]);
    }

    public static Double median (int[] a1, int[] a2) {
        if (a1.length != a2.length) throw new IllegalArgumentException("The argument thrown is illegal");

        int lb = 0;
        int hb = a1.length - 1;

        while (lb <= hb) {
            int a1Median = (lb + hb)/2;
            int a2Median = (a2.length - 1) - a1Median;

            if (isMedian(a1, a2, a1Median) || isMedian(a2, a1, a2Median)) {
                return (a1[a1Median] + a2[a2Median])/2.0;
            }

            if (a1[a1Median] < a2[a2Median]) {
                lb = a1Median + 1;
            }

            if (a1[a1Median] > a2[a2Median]) {
                hb = a1Median - 1;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        int[] a1 = {1, 3, 5, 7, 9};
        int[] a2 = {2, 4, 6, 8, 10};
        System.out.println("Expected 5.5, Actual " + median (a1, a2));


        int[] a3 = {1, 3, 5, 7, 9, 100};
        int[] a4 = {2, 4, 6, 8, 10, 200};
        System.out.println("Expected 6.5, Actual " + median (a3, a4));

        int[] a5 = {1, 2, 3, 4};
        int[] a6 = {5, 6, 7, 8};
        System.out.println("Expected 4.5, Actual " + median (a5, a6));

        int[] a7 = {5, 6, 7, 8};
        int[] a8 = {1, 2, 3, 4};
        System.out.println("Expected 4.5, Actual " + median (a7, a8));  
    }
}

The function median returns a primitive wrapper Double rather than double simply because it's forced to do so.

If median is not found then returning -1 may not be the right choice since, -1 may also be a valid median. In this case, unlike binary search, I dont return a index of an array and dont want to do it either.

Last option which I have is to throw an exception. But coming to my question: is function median a valid use of a primitive wrapper of just an unwanted hack?

Was it helpful?

Solution

No that's fine. Your other choice is to create a wrapper object like

class MedianAnswer {
  boolean success;  
  double median;
}

and return that instead, and to check medianAnswer.success to see if it found the median.

An additional option is to throw MedianNotFoundException and to catch it. You do similar with IllegalArgumentException.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top