分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
//****************************************************************************************************//// 求n个数的中位数 - C++ - by Chimomo//// 对于一组有限个数的数据来说,它们的中位数是这样的一种数:这群数据里的一半的数据比它大,而另外一半数据比它小。// 计算有限个数的数据的中位数的方法是:把所有的同类数据按照大小的顺序排列。如果数据的个数是奇数,则中间那个数据就是这群数据的中位数;如果数据的个数是偶数,则中间那2个数据的算术平均值就是这群数据的中位数。////****************************************************************************************************#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[9] = {-5, 345, 88, 203, 554, 1, 89, 909, 1001}; cout << EvaluateMedian(a, 9) << endl; return 0;}// Output:/*203*/