首页 > 编程语言 > 详细

c++求中位数

时间:2019-08-22 16:23:42      阅读:96      评论:0      收藏:0      [点我收藏+]
技术分享图片
#include <iostream>
#include <cassert>
#include <stack>
#include <math.h>
 
using namespace std;
 
int QuickSortOnce(int a[], int low, int high) {
    // 将首元素作为枢轴。
    int pivot = a[low];
    int i = low, j = high;
 
    while (i < j) {
        // 从右到左,寻找首个小于pivot的元素。
        while (a[j] >= pivot && i < j) {
            j--;
        }
 
        // 执行到此,j已指向从右端起首个小于或等于pivot的元素。
        // 执行替换。
        a[i] = a[j];
 
        // 从左到右,寻找首个大于pivot的元素。
        while (a[i] <= pivot && i < j) {
            i++;
        }
 
        // 执行到此,i已指向从左端起首个大于或等于pivot的元素。
        // 执行替换。
        a[j] = a[i];
    }
 
    // 退出while循环,执行至此,必定是i=j的情况。
    // i(或j)指向的即是枢轴的位置,定位该趟排序的枢轴并将该位置返回。
    a[i] = pivot;
 
    return i;
}
 
void QuickSort(int a[], int low, int high) {
    if (low >= high) {
        return;
    }
 
    int pivot = QuickSortOnce(a, low, high);
 
    // 对枢轴的左端进行排序。
    QuickSort(a, low, pivot - 1);
 
    // 对枢轴的右端进行排序。
    QuickSort(a, pivot + 1, high);
}
 
int EvaluateMedian(int a[], int n) {
    QuickSort(a, 0, n - 1);
 
    if (n % 2 != 0) {
        return a[n / 2];
    } else {
        return (a[n / 2] + a[n / 2 - 1]) / 2;
    }
}
 
int main() {
    int a[11] = {-5, 345, 88, 204, 205,203, 554, 1, 89, 909, 1001};
    cout << EvaluateMedian(a, 11) << endl;
    return 0;
}
View Code

 

c++求中位数

原文:https://www.cnblogs.com/gary-guo/p/11394932.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!