本題要求實現(xiàn)一個函數(shù),求N個集合元素A[]的中位數(shù),即序列中第[N/2+1]大的元素。其中集合元素的類型為自定義的ElementType。
函數(shù)接口定義:
ElementType Median( ElementType A[], int N );
其中給定集合元素存放在數(shù)組A[]中,正整數(shù)N是數(shù)組元素個數(shù)。該函數(shù)須返回N個A[]元素的中位數(shù),其值也必須是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_s("%d", &N);
for (i = 0; i<N; i++)
scanf_s("%f", &A[i]);
printf("%.2f\n", Median(A, N));
getchar();
getchar();
return 0;
}
/* 你的代碼將被嵌在這里 */
ElementType Median(ElementType A[], int N)
{
float temp = A[0];
for (int i = 0; i < N; i++)
for (int j = 1; j < N - i; j++)
{
if (A[j] < A[j - 1])
{
temp = A[j];
A[j] = A[j - 1];
A[j - 1] = temp;
}
else;
}
return A[(int)N / 2];
}
先采用冒泡排序?qū)崿F(xiàn)數(shù)組的排序,然后直接輸出中位數(shù)。
在提交過程中,出現(xiàn)運行超時的情況,并沒有實現(xiàn)這塊的優(yōu)化,待更新優(yōu)化。。。