zoukankan      html  css  js  c++  java
  • 寻找中位数--快速排序

    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); 
    }
  • 相关阅读:
    [单调栈] Jzoj P4260 最大子矩阵
    [前缀和] Jzoj P4259 矩形
    [欧拉回路][状压dp] Jzoj P3290 吃货JYY
    [组合数][枚举] Jzoj P3332 棋盘游戏
    [欧拉函数][dp][快速幂] Jzoj P1161 机器人M号
    [exgcd] Jzoj P1158 荒岛野人
    [带权并查集] Jzoj P1503 体育场
    [dfs][树的直径] Jzoj P1737 删边
    [差分][倍增lca][tarjan] Jzoj P3325 压力
    [dfs] Jzoj P1497 景点中心
  • 原文地址:https://www.cnblogs.com/brock-1993/p/3741470.html
Copyright © 2011-2022 走看看