log(m+n)时间找到中位数

昨天晚上我的室友出了一道题目:

现在有两个已经有序的数组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;
}
一些细节的问题还是要考虑清楚的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值