1
\$\begingroup\$

How will you merge two sorted arrays, when The longer array has empty spaces to accomodate the second array. Complexity: O (items in longer + items in smaller). Request for making code concise, clean and optimal.

public final class MergeArrays {

    private MergeArrays() {}

    private static void check(Integer[] big, Integer[] small) {
        if (big == null && small == null) {
            throw new NullPointerException("The input arrays are null.");
        }

        if (big.length < small.length) {
            throw new IllegalArgumentException("The arrays is smaller smaller array");
        }
    }

    public static Integer[] mergeSortedArrays(Integer[] big, Integer[] small) {
        check(big, small);
        int limit = 0;
        for (Integer val : big) {
            if (val == null) { break; }
            limit++;
        }
        return mergeSortedArrays(big, limit, small);
    }

    private static Integer[] mergeSortedArrays(Integer[] big, int limit, Integer[] small) {
        assert big != null;
        assert small != null;

        int limitIndex = limit - 1;
        int bigIndex = big.length - 1;
        int smallIndex = small.length - 1; 

        while (smallIndex >= 0) {
            if (limitIndex < 0 || big[limitIndex] < small[smallIndex]) {
                big[bigIndex--] = small[smallIndex--];
            } else {
                big[bigIndex--] = big[limitIndex--];
            }
        }

        return big;
    }
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Do not throw NullPointerException when arguments are null. NPE is thrown when you are trying to access properties and methods of null reference. Not when you are checking on some preconditions. Throw IllegalArgumentException as you do in length validation. In other method you use assertions. Chose one method and stick with it, dont mix them.

You don have to define empty constructor. It is created implicitly.

\$\endgroup\$
1
  • \$\begingroup\$ In this case, the empty constructor needs to be defined because it is marked private. An implicit empty constructor is always public. \$\endgroup\$ Commented Nov 21, 2013 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.