寻找两个有序数组的中位数——C++实现

程序分析:
(1)如果一个序列有奇数个,中位数是最中间的那个数;
(2)如果一个序列有偶数个,中位数是最中间的两个数的平均数。

C++代码:

#include
using namespace std;

int min(int a, int b) {
	if (a > b) {
		return b;
	}
	else {
		return a;
	}
}

double find(int A[], int m, int B[], int n, int k) {
	if (m>n) {
		return find(B, n, A, m, k);
	}
	if (m == 0) {
		return B[k - 1];
	}
	if (k == 1) {
		return min(A[0], B[0]);
	}

	int pa = min(k / 2, m), pb = k - pa;
	if (A[pa - 1]>B[pb - 1]) {
		return find(A, m, B + pb, n - pb, k - pb);
	}
	else if (A[pa - 1]<B[pb - 1]) {
		return find(A + pa, m - pa, B, n, k - pa);
	}
	else {
		return A[pa - 1];
	}
}

double findMedianSortedArrays(int A[], int m, int B[], int n) {
	int total = m + n;
	if (total & 1) {
		return find(A, m, B, n, total / 2 + 1);
	}
	else {
		return (find(A, m, B, n, total / 2) + find(A, m, B, n, total / 2 + 1)) / 2;
	}
}


int main() {
	int A[100],B[100];
	int m,n,num;

	cout << "Please input the number of array:";
	cin >> m>>n;
	
	cout << "Please input the first array:";
	for (int i = 0; i < m; i++) {
		cin >> A[i];
	}
	cout << "Please input the second array:";
	for (int i = 0; i < n; i++) {
		cin >> B[i];
	}

	num = findMedianSortedArrays(A, m, B, n);
	cout << "The median of two arrays:" << num << endl;

	return 0;
}

C++运行结果:
寻找两个有序数组的中位数——C++实现_第1张图片

你可能感兴趣的:(数组)