Find the Median of Two Ascending Sequences (Subtract and Conquer)

topic:

In an ascending sequence S of length L (L≥1), the number at the L/2th position (if it is a decimal, add 1 after removing the decimal) is called the median of S. For example, if the sequence S1=(11, 13, 15, 17, 19), then the median of S1 is 15. The median of two sequences is the median of the ascending sequence with all their elements. For example, if S2=(2, 4, 6, 8, 20), then the median of S1 and S2 is 11. Given two equal-length ascending sequences A and B, try to implement an algorithm that is as efficient as possible in both time and space to find the median of the two sequences A and B.
 

Problem solving diagram:

 Code:

public class SearchMid {
    public static void main(String[] args) {
        int arr1[] = {11, 13, 15, 17, 19};
        int arr2[] = {2, 4, 6, 8, 20};

        System.out.println("中位数:"+searchMid(arr1, arr2, arr1.length - 1));

    }

    private static int searchMid(int[] arr1, int[] arr2, int n) {
        int start1 = 0, start2 = 0, end1 = n, end2 = n, mid1 = 0, mid2 = 0;


        while (end1 > start1 && end2 > start2) {
            mid1 = (start1 + end1) / 2;
            mid2 = (start2 + end2) / 2;


            if (arr1[mid1] == arr2[mid2]) {
                return arr1[mid1];
            }
            if (arr1[mid1] < arr2[mid2]) {
//                if ((end1-start1)%2==0){
//                    start1=mid1;
//                }
//                else{
//                    start1=mid1+1;
//                }

                start1 = (end1 - start1) % 2 == 0 ? mid1 : mid1 + 1;
                end2 = mid2;
            } else {
                end1 = mid1;
                start2 = (end2 - start2) % 2 == 0 ? mid2 : mid2 + 1;
//                if ((end2-start2)%2==0){
//                    start2=mid2;
//                }
//                else {
//                    start2=mid2+1;
//                }


            }


        }

        return arr1[start1] > arr2[start2] ? arr2[start2] : arr1[start1];

//        if (arr1[start1]>arr2[start2]){
//            return arr2[start2];
//        }
//        else  return arr1[start1];


    }


}

Guess you like

Origin blog.csdn.net/Javascript_tsj/article/details/123906145