中位数

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

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

输出描述:
输出中位数,每一组测试数据输出一行。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main(){
    int n, m;
    while(cin >> n){
        if(n == 0)break;
        vector<int> arr;
        for(int i = 0; i < n; ++i){
            cin >> m;
            arr.push_back(m);
        }
        sort(arr.begin(), arr.end());
        if(n % 2 == 0){
            cout << int((arr[n / 2] + arr[(n / 2) - 1]) / 2) << endl;
        }else{
            cout << arr[n / 2] << endl;
        }
    }
    return 0;
}

改进:

#include<stdio.h>
#include<algorithm>
using namespace std;

int num[10000];

int main(){
    int n ; 
    while(scanf("%d",&n)!=EOF&&n!=0){
        for(int i=0;i<n;i++){
            scanf("%d",&num[i]);
        }
        sort(num,num+n);
        int a= n-1;
        if(n%2==1){
            printf("%d\n",num[a/2]);
        }else{
            printf("%d\n",(num[a/2]+num[(a/2)+1])/2);
        }
        
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值