寻找中位数--快速排序

 

Description

Given an odd number N (1 <= N < 10,000) and N integers (1..1,000,000), find their median .

 

Input

* Line 1: A single integer N 

*
 Lines 2..N+1: Each line contains a single integer.

 

Output

* Line 1: A single integer that is the median of these N integers.

 

Sample Input

5
2
4
1
3
5

Sample Output

3
//寻找中位数

#include<iostream>
#include<cstdlib>
using namespace std;
//快速排序
void qsort(int *ptr, int begin, int end);

int main()
{
    cin.get();
    cin.clear();
    cout<<"A single integer: ";
    int N=0,i=0;
    while(true)
    {
        cin>>N;
        if(N%2)
            break;
        cout<<"Please enter a single integer: ";
    }
    int *arrayN = new int[N];
    while(i<N&&cin>>arrayN[i])
    {
        i++;
    }
    qsort(arrayN,0,N-1);
    cout<<"The median of these N integers is "<<arrayN[(N-1)/2]<<endl;
    system("pause");
    return 0;
}
void qsort(int *ptr, int begin, int end)
{
    int temp = *(ptr + begin);//设置初始比较基准数据
    int i = begin + 1, j = end, curPosition = begin;//定义开头和结尾的I j
    bool direction = false;
    while(i <= j)
    {
        if(direction)
        {
            if(*(ptr + i) < temp)//如果当前数据小于基准数据 那么换位置 改当前位置
            {
                *(ptr + curPosition) = *(ptr + i);
                curPosition = i;
                direction = false;
            }
            i++;
        }else//先从后到前比较数据
        {
            if(*(ptr + j) > temp)//如果最后一个大于基准 那么最后一个数据赋值给当前基准数据的那个位置 调整基准数据的位置
            {
                *(ptr + curPosition) = *(ptr + j);//
                curPosition = j;
                direction = true;
            }
            j--;
        }
    }     

    *(ptr + curPosition) = temp;   
    if(curPosition - begin > 1)//前面小的比较
        qsort(ptr, begin, curPosition - 1);
    if(end - curPosition > 1)//后面大的比较
        qsort(ptr, curPosition + 1, end); 
}

 

转载于:https://www.cnblogs.com/brock-1993/p/3741470.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值