寻找中位数(不添加新数组)
题目问题描述:
一个长度为L的升序序列S,处在[L/2]个位置的数称为S的中位数例如,若序列S1=(11,13,15,17,19)则S1的中位数是15,两个序列的中位数是含他们所有的生序序列的中位数例如若S2=(2,4,6,8,20)则S1和S2的的中位数是11.现在有两个等长的生序序列A和B,是设计一个算法求两个序列的中位数
结果截图:
合并思想,但不放入新数组,利用count来计算寻找中位数(len)
实现代码:
//寻找中位数(不添加新数组)
#include<stdio.h>
int main(){
int s1[5] = {11,13,15,17,19};
int s2[5] = {2,4,6,8,20};
int len = 4;
int i = 0,j = 0;
int count = 0;
while(i < 5 && j < 5){
if(s1[i] < s2[j]){
if(count == len){
printf("%d\n",s1[i]);
return 0;
}
count++;
i++;
}
else{
if(count == len){
printf("%d\n",s2[j]);
return 0;
}
count++;
j++;
}
}
while(i < 5){
if(count == len){
printf("%d\n",s1[i]);
return 0;
}
count++;
i++;
}
while(i < 5){
if(count == len){
printf("%d\n",s2[j]);
return 0;
}
count++;
j++;
}
}