c++求中位数

#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

 

posted on 2019-08-22 16:07  gary_123  阅读(2373)  评论(0编辑  收藏  举报

导航