中位数

题目链接:https://www.nowcoder.com/practice/2364ff2463984f09904170cf6f67f69a?tpId=40&tqId=21367&tPage=2&rp=1&ru=%2Fta%2Fkaoyan&qru=%2Fta%2Fkaoyan%2Fquestion-ranking

题目描述

中位数定义:一组数据按从小到大的顺序依次排列,处在中间位置的一个数(或最中间两个数据的平均数). 给出一组无序整数,求出中位数,如果求最中间两个数的平均数,向下取整即可(不需要使用浮点数)

输入描述:

该程序包含多组测试数据,每一组测试数据的第一行为N,代表该组测试数据包含的数据个数,1<=N<=10000.
接着N行为N个数据的输入,N=0时结束输入

输出描述:

输出中位数,每一组测试数据输出一行
示例1

输入

4
10
30
20
40
3
40
30
50
4
1
2
3
4
0

输出

25
40
2

 1 #include <iostream>
 2 #include <string>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <cmath>
 6 #include <stack>
 7 using namespace std;
 8 int a[10010];
 9 int main()
10 {
11     int n;
12     while(cin>>n&&n!=0){
13         for(int i=0;i<n;i++){
14             cin>>a[i];
15         }
16         sort(a,a+n);
17         if(n%2!=0){
18             cout<<a[n/2]<<endl;
19         }
20         else cout<<(a[n/2]+a[n/2-1])/2<<endl;
21     }
22     return 0;
23 }
原文地址:https://www.cnblogs.com/shixinzei/p/8072075.html