1. 程式人生 > >求指定整數數組的中位數

求指定整數數組的中位數

數組 ets %d 指定 message In eof arr TP

//int a[]={12,43,56,14,78,16,50,26,30,40};的中位數
//按數據從小到大排序,如果是奇數個數字,則中間那個數字為中位數;如果是偶數個數字,則中間2個數字的平均值為中位數。

int getSortedArr(int * a,int len)
{
int i,j,temp;
int index,result;
for(i=0;i<len;i++)
{
for(j=i+1;j<len;j++)
{
if(a[j]<a[i])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

index=len%2;

if(index==0)
{
result=(a[len/2-1]+a[len/2])/2;
}else
{
result=a[len/2];
}

// for(i=0;i<len;i++)
// {
// lr_output_message("%d",a[i]);
// }

return result;
}

Action()
{
int a[]={12,43,56,14,78,16,50,26,30,40};

int len=sizeof(a)/sizeof(int);

int result=getSortedArr(a,len);

lr_output_message("中位數為:%d",result);

return 0;
}

求指定整數數組的中位數