web123456

7-3 Median of two ordered sequences (20 points)

#include <iostream> using namespace std; void find(int a[], int a_l, int a_r, int b[], int b_l, int b_r) { int m1, m2; //If the search array contains two numbers, directly find the median 4 6 /2 3 m1 takes 4, m2 takes 3 if (a_r - a_l == 1) { //The first median is the larger of the starting elements of the two arrays m1=a[a_l]<b[b_l]? b[b_l]:a[a_l]; //The second median is the smaller of the end elements of the two arrays m2=a[a_r]<b[b_r]? a[a_r]:b[b_r]; if (m1 < m2) cout << m1 << endl; else cout << m2 << endl; return; } //If the number of array elements is odd, m will take the middle number. //If the number of array elements is even, there are two medians, m1 takes the larger of the two medians. m1 = (a_l + a_r + 1) / 2; //If the number of array elements is even, there are two medians, m2 takes the smaller of the two medians. m2 = (b_l + b_r) / 2; //If two medians ab are equal, a[m1]=a[m2] is the median if(a[m1] == b[m2]) { cout << a[m1] << endl; return; } if(a[m1] < b[m2]) //The search range of the first array is the right half, and the search range of the second array is the left half. find(a, m1, a_r, b, b_l, m2); else //The search range of the first array is the left half, and the search range of the second array is the right half. find(a, a_l, m1, b, m2, b_r); return; } int main() { int n; cin >> n; int a[n]; int b[n]; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; find(a, 0, n - 1, b, 0, n - 1); return 0; }