1622 - 中位数
中位数定义:一组数据按从小到大的顺序依次排列,处在中间位置的一个数(或最中间两个数据的平均数).
给出一组无序整数,求出中位数,如果求最中间两个数的平均数,向下取整即可(不需要使用浮点数)
Input
该程序包含多组测试数据,每一组测试数据的第一行为N,代表该组测试数据包含的数据个数,1<=N<=10000.
接着N行为N个数据的输入,N=0时结束输入
Output
输出中位数,每一组测试数据输出一行
Examples
Input
1 468 15 501 170 725 479 359 963 465 706 146 282 828 962 492 996 943 0
Output
468 501
Hint
按题目要求模拟即可
Solution C
#include <stdio.h> int main() { int n,i,j,temp,p; int a[10000]; scanf("%d",&n); while( n!= 0 ) { for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=1;i<n;i++) { temp = a[i]; for(j=i-1;j>=0 && temp<a[j];j--) { a[j+1]=a[j]; } a[j+1]=temp; } if(n%2 != 0) printf("%d\n",a[n/2]); else if(n%2==0) { p=(a[n/2]+a[(n/2)-1] )/2; printf("%d\n",p); } scanf("%d",&n); } return 0; }
Solution C++
#include <iostream> #include <algorithm> using namespace std; int main() { int n;cin>>n; while(n!=0) { int *arr = new int[n]; for(int i=0; i<n; ++i) cin>>arr[i]; sort(arr,arr+n); int mid = n>>1; if(n&1==1) cout<<arr[mid]<<endl; else cout<<((arr[mid-1]+arr[mid])>>1)<<endl; cin>>n; } return 0; }
Hint
按题目要求模拟即可