C语言求中位数递归算法
合集下载
相关主题
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include<stdio.h> #include<malloc.h> typedef int ElementType; ElementType Median(ElementType S[],int N); ElementType FindKthLargest(ElementType S[],int K,int left,int right,ElementType t[]); int main() {
if(S[i]>=e) t[Large++]=S[i];
else t[Small--]=S[i];
if(Small==right&&right>left) {
e=S[right]; S[right]=S[left]; S[left]=e; Large=left; for(i=left;i<=right;i++)
else return FindKthLargest(S,K-Large+left,Larg源自文库,right,t);
}
if(S[i]=e) t[Large++]=S[i];
else t[Small--]=S[i];
} for(i=left;i<=right;i++)
S[i]=t[i]; if(K<Large-left)
return FindKthLargest(S,K,left,Large-1,t);
if(K==Large-left) return e;
int a[]={6,5,9,8,2,1,7,3,4}; printf("中位数是:%d\n",Median(a,9)); } ElementType Median(ElementType S[],int N) { ElementType *p,m; p=(ElementType *)malloc(sizeof(ElementType)*N); m=FindKthLargest(S,(N+1)/2,0,N-1,p); free(p); return m; } ElementType FindKthLargest(ElementType S[],int K,int left,int right,ElementType t[]) { int i,Large=left,Small=right; ElementType e; e=S[left]; for(i=left;i<=right;i++)
if(S[i]>=e) t[Large++]=S[i];
else t[Small--]=S[i];
if(Small==right&&right>left) {
e=S[right]; S[right]=S[left]; S[left]=e; Large=left; for(i=left;i<=right;i++)
else return FindKthLargest(S,K-Large+left,Larg源自文库,right,t);
}
if(S[i]=e) t[Large++]=S[i];
else t[Small--]=S[i];
} for(i=left;i<=right;i++)
S[i]=t[i]; if(K<Large-left)
return FindKthLargest(S,K,left,Large-1,t);
if(K==Large-left) return e;
int a[]={6,5,9,8,2,1,7,3,4}; printf("中位数是:%d\n",Median(a,9)); } ElementType Median(ElementType S[],int N) { ElementType *p,m; p=(ElementType *)malloc(sizeof(ElementType)*N); m=FindKthLargest(S,(N+1)/2,0,N-1,p); free(p); return m; } ElementType FindKthLargest(ElementType S[],int K,int left,int right,ElementType t[]) { int i,Large=left,Small=right; ElementType e; e=S[left]; for(i=left;i<=right;i++)