昨天晚上我的室友出了一道题目:
现在有两个已经有序的数组A和B,A有m个元素,B有n个元素。现在使用log(m+n)的复杂度计算出它们的中位数。我大致想了一下,用分治算法。然后今天写出了代码:
/*
This file implements :
For two ordered arrays A with m integers and B with n integers.
please find the median number within log(m + n) time.
*/
#include <stdio.h>
void find_median_number(int A[], int start_1, int B[], int start_2, int kth_smallest, int size_of_A, int size_of_B) {
int temp;
int end_1;
int end_2;
int compare_from_A;
int compare_from_B;
int bound = 0;
while (1) {
bound = 0;
if (start_1 >= size_of_A) {
start_1 = size_of_A - 1;
}
if (start_2 >= size_of_B) {
start_2 = size_of_B - 1;
}
if (1 == kth_smallest) {
temp = A[start_1] > B[start_2] ? B[start_2] : A[start_1];
fprintf(stdout, " median : %d \n", temp);
return;
}
end_1 = start_1 + (kth_smallest + 1) / 2 - 1;
end_2 = start_2 + (kth_smallest + 1) / 2 - 1;
if (end_1 >= size_of_A) {
end_1 = size_of_A - 1;
bound = 1;
}
if (end_2 >= size_of_B) {
end_2 = size_of_B - 1;
bound = 2;
}
compare_from_A = A[end_1];
compare_from_B = B[end_2];
if (compare_from_A > compare_from_B) {
if (2 == bound) {
/*stop*/
temp = start_1 + kth_smallest - (end_2 - start_1 + 1) - 1;
fprintf(stdout, "median : %d\n", A[temp]);
return;
}
start_2 = end_2 + 1;
} else {
start_1 = end_1 + 1;
if (1 == bound) {
/*stop*/
temp = start_2 + kth_smallest - (end_1 - start_1 + 1) - 1;
fprintf(stdout, "median : %d\n", B[temp]);
return;
}
}
kth_smallest = (kth_smallest + 1) / 2;
}
//find_median_number(A, start_1, B, start_2, (kth_smallest + 1) / 2, size_of_A, size_of_B);
}
int main() {
int a[] = {1, 2, 3, 4, 5 , 6, 7, 8, 9, 10};
int b[] = {1, 2, 3 };
int kth_smallest = (sizeof(a) / sizeof(int) + sizeof(b) / sizeof(int) + 1) / 2;
find_median_number(a, 0, b, 0, kth_smallest, sizeof(a) / sizeof(int), sizeof(b) / sizeof(int));
return 0;
}
一些细节的问题还是要考虑清楚的。