本题要求实现一个函数,求N个集合元素A[]的中位数,即序列中第⌊(N+1)/2⌋大的元素。其中集合元素的类型为自定义的ElementType。
函数接口定义:
ElementType Median( ElementType A[], int N );
其中给定集合元素存放在数组A[]中,正整数N是数组元素个数。该函数须返回N个A[]元素的中位数,其值也必须是ElementType类型。
裁判测试程序样例:
#include <stdio.h>
#define MAXN 10
typedef float ElementType;
ElementType Median( ElementType A[], int N );
int main ()
{
ElementType A[MAXN];
int N, i;
scanf("%d", &N);
for ( i=0; i<N; i++ )
scanf("%f", &A[i]);
printf("%.2f\n", Median(A, N));
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
3
12.3 34 -5
输出样例:
12.30
别看他简简单单的求个中位数,作为菜鸡的我被坑的不要不要的…
不信邪的我在电脑前做了一中午,决定试下我能用的所有排序
- 冒泡排序(当然不行)
- 插入排序(当然也不行)
- 快速排序 (当然还是不行)
- 看到大佬们都用希尔排序过了,我决定这个排序再缓缓
- 堆排序
错误代码:
void swap(ElementType *a ,ElementType *b){
ElementType temp;
temp=*a;
*a=*b;
*b=temp;
}
ElementType mp( ElementType A[], int N ){
float t;
for(int i=0;i<N-1;i++){
for(int j=0;j<N-i-1;j++){
if(A[j]>A[j+1]){
t=A[j];
A[j]=A[j+1];
A[j+1]=t;
}
}
}
int mid=N/2;
return A[mid];
}
ElementType Median3( ElementType A[],int left,int right){
int mid=(left+right)/2;
if(A[left]>A[mid]){
swap(&A[left],&A[mid]);
}
if(A[left]>A[right]){
swap(&A[left],&A[right]);
}
if(A[mid]>A[right]){
swap(&A[mid],&A[right]);
}
swap(&A[mid],&A[right-1]);
return A[right-1];
}
void Q_sort(ElementType A[],int left,int right)
{
if(right-left>=100){
int i=left,j=right-1;
ElementType pivot=Median3(A,left,right);
for(;;){
while(A[++i]<pivot){}
while(A[--j]>pivot){}
if(i<j){
swap(&A[i],&A[j]);
}else{
break;
}
}
swap(&A[i],&A[right-1]);
Q_sort(A,left,i-1);
Q_sort(A,i+1,right);
}else{
mp(A,right+1);
}
}
/* 你的代码将被嵌在这里 */
ElementType Median( ElementType A[], int N ){
mp(A,N);
//Q_sort(A,0,N-1);
return A[N/2];
}
历经两小时…
我还是没有用希尔排序!因为我傲娇
使用堆排序 AC 了
void swap(ElementType *a ,ElementType *b){
ElementType temp;
temp=*a;
*a=*b;
*b=temp;
}
void percDown(ElementType A[],int i,int N){
int child;
ElementType tmp;
for(tmp=A[i];2*i+1<N;i=child){ //subtree also need percdown
child = 2*i+1;
if(child!=N-1 && A[child+1]>A[child])
child++;//find bigger value for swap
if(tmp<A[child])
A[i]=A[child];
else
break;
}
A[i] = tmp;
}
void Head_sort(ElementType A[],int N){
int i;
for(i=N/2;i>=0;i--){
percDown(A,i,N);
}
for(i=N-1;i>0;i--){
swap(&A[0],&A[i]);
percDown(A,0,i);
}
}
/* 你的代码将被嵌在这里 */
ElementType Median( ElementType A[], int N ){
Head_sort(A,N);
return A[N/2];
}
陈越姥姥是大佬!!!我慕了