median of two sorted arrays

后端 未结 10 646
南旧
南旧 2020-12-16 19:12

My question is with reference to Method 2 of this link. Here two equal length sorted arrays are given and we have to find the median of the two arrays merged.



        
10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 19:52

    Let me help you visualize it. Lets say it is case 3, the same argument follows for the other case. That means we have identified the median is present in 1st half of ar1 or second half of ar2. Now the question is why is the median of these halves same as the median of the original arrays, right.

    So visualize putting just these relevant halves together in sorted order and finding its median. Now put the other left over halves back into this picture, where would they go. The first half of ar2, all n/2 elements have to go to the top of this new median and second half of arr1 all n/2 elements will have to go below this median (the exact locations is unimportant for median). So that means it will still be a median as equal number of elements are added above and below it. So the median of the two new halves is same as the median of the original set.

    To be still more precise, let's see why first half of ar2 (a leftover half) has to go above the new median. That is the case because when we put all the elements together m2 has to go above the new median(since m2 < m1) which means all the first half of ar2 also have to go above the new median. In other words if m is the new median of the 2 selected halves, m2 < m => all first half of ar2 < m. Similar argument for the lower half of ar1. This means the new median m will remain the median of the entire set.

    Looking more closely at your algo., though the approach is correct there might be a slight error in the algo while taking care of odd and even cases so beware while implementing.

提交回复
热议问题