- 通过示例学习 C,是时候了
- 通过示例学习 C - 主页
- C 示例- 简单程序
- C 示例- 循环/迭代
- C 示例- 模式
- C 示例- 数组
- C 示例- 字符串
- C 示例- 数学
- C 示例- 链表
- C 编程有用资源
- 通过示例学习 C - 快速指南
- 通过示例学习 C - 资源
- 通过示例学习 C - 讨论
C 语言中的中位数程序
中位数是排序列表中居中的值。要找到中位数,我们需将列表按升序或降序排序。
例如,将 3、5、2、7、3 列表作为输入列表。要找出中位数,我们首先重新排列为 2、3、3、5、7。我们发现位置为 3 的值 ((5 + 1)/2) 是 3。因此此列表中的中位数为 3。
算法
此程序的算法非常简单 −
START Step 1 → Take an integer list A of n values Step 2 → Arrange the values in the list in some order, say ascending Step 3 → Calculate the middle of list → (n + 1) / 2 Step 4 → Display the middle value as median STOP
伪代码
我们可以根据算法导出伪代码,如下 -
procedure median() Array A Size N SORT(A) middle = (N + 1) / 2 DISPLAY A[middle] as median end procedure
实现
此算法的实现如下 −
#include <stdio.h>
void swap(int *p,int *q) {
int t;
t=*p;
*p=*q;
*q=t;
}
void sort(int a[],int n) {
int i,j,temp;
for(i = 0;i < n-1;i++) {
for(j = 0;j < n-i-1;j++) {
if(a[j] > a[j+1])
swap(&a[j],&a[j+1]);
}
}
}
int main() {
int a[] = {6,3,8,5,1};
int n = 5;
int sum,i;
sort(a,n);
n = (n+1) / 2 - 1; // -1 as array indexing in C starts from 0
printf("Median = %d ", a[n]);
return 0;
}
输出
程序输出应该是 −
Median = 5
mathematical_programs_in_c.htm
广告