Two ordered arrays, each containing n elements, for the nth-largest element
1. Sequential traversal of two arrays, count variable K statistical occurrence of the K small element, the time complexity of O (n)
The code is as follows:
int getmid (int a[],int b[],int n) {int k=0;int i=0,j=0;while (i<n&&j<n) {if (A[i]<b[j]) {i++;k++;if (k==n ) return a[i-1];} else {j++;k++;if (k==n) return b[j-1];}}}
2. Two-point method
Take the middle element of a array mid1, take the middle element of B array Mid2, compare the size of these two elements first. Assuming that the two elements are equal, return directly to A[MID1], assuming A[MID1]<B[MID2], then the elements on the left side of the MID1 can be removed, and the elements on the right side of the B array can be removed. Here also to distinguish the number of array elements is even odd, assuming that the number of elements is even, then the MID1 element should be removed. Suppose A[mid1]<b[mid2] is similar in this case. Time Complexity of O (LOGN)
# include <iostream># include <cstdlib>using namespace std;int mid (int a[],int b[],int n) {int s1=0,e1=n-1;int S2=0,e2=n-1;int mid1= (s1+e1)/2;int mid2= (s2+e2)/2;while (s1!=e1| | S2!=E2) {mid1= (s1+e1)/2;mid2= (s2+e2)/2;if (A[mid1]==b[mid2]) {return A[MID1];} if (A[mid1]<b[mid2]) {if ((s1+e1)%2==0) {S1=mid1;e2=mid2;} else {S1=mid1+1;e2=mid2;}} Else{if ((s1+e1)%2==0) {E1=mid1;s2=mid2;} else{e1=mid1;s2=mid2+1;}}} Return A[S1]<B[S2]?A[S1]:B[S2];} int main () {int a[5]={2,4,5,6,9};int b[5]={1,3,7,8,10};cout<<mid (a,b,5) <<endl;system ("pause"); return 0;}
The nth large number of two ordered arrays