Find kth smallest element from two sorted arrays
<p>Given two sorted array of size M and N. I was trying to implement an algorithm with time complexity O(logM+logN). The strategy is basically comparing the middle index elements from two subarray based on their length condition.</p>

<pre><code>    // Test case 1
    // Works for all position except when kth is 6
    int[] num1 = {6,7,8,9,10,11,12};
    int[] num2 = {1,2,3,4,5};

    // Test case 2
    // Always print the next smallest element
    int[] num3 = {1,3,5,7,9};
    int[] num4 = {2,4,6,8,10,12,14,16,18,20,22,24,30,40,50,56,77,35};


public static int findKth(int[] A, int p1, int r1, int[] B, int p2, int r2, int k){


    if (p1 &gt; r1) { 
        return B[p2+k-1];
    } else if (p2 &gt; r2) {
        return A[p1+k-1];
    }


    int midA = p1 + (int)Math.floor((r1-p1)/2);// Middle element from subarray A
    int midB = p2 + (int)Math.floor((r2-p2)/2);// Middle element from subarray B

    /**
     * Compare the sum of number of elements from left-subarray up to middle element. 
     */
    if ((midA-p1+midB-p2+2) &lt; k) { 
        // We don't need to the left-subarray based on the comparisons between middle element
        if (A[midA] &gt; B[midB]) {
            return findKth(A, p1, r1, B, midB+1, r2, k-(midB-p2+1)); //
        } else {
            return findKth(A, midA+1, r1, B, p2, r2, k-(midA-p1+1)); //
        }
    } else {
        // We don't need to the right-subarray based on the comparisons between middle element.
        if (A[midA] &gt; B[midB]) {
            return findKth(A, p1, midA-1, B, p2, r2, k);
        } else {
            return findKth(A, p1, r1, B, p2, midB-1, k);
        }
    }
}
</code></pre>

<p>I felt the strategy I used should be correct. But for the two test cases shown above, it'll print wrong outputs in some particular kth value. So I guessed there must be something wrong with my strategy. Can anyone describe briefly which part of this implementation is not correct? Thanks!</p>