题目描述:Median ValueThe Median is the "middle" of a sorted list of numbers.How to Find the Median ValueTo find the Median, place the numbers in value order and find the middle.Example: find the Median of 12, 3 and 5Put them in order:3, 5, 12The middle is 5, so the median is 5.
// 经典折半查找int parition(int* pArr, int begin, int end){ if (pArr == NULL || begin>end) { return -1; } //showData(pArr, 7); int temp = pArr[begin]; while (end>begin) { // == while (end>begin && pArr[end] >= temp) { end--; } pArr[begin] = pArr[end]; while (end>begin && pArr[begin] <= temp) { begin++; } pArr[end] = pArr[begin]; } pArr[begin] = temp; cout << "mid=" << begin << ":" << temp<< endl; showData(pArr, 7); return begin;}/************************************************************************/// Find the Median// {4,5,1,6,2,7,3,8}// // 分析:// 中位数位置就是 i=len/2// // 实现方式// 1 递归 // // @input:mid=len/2 // /************************************************************************/int GetMedianNumber(int* pArr, int begin,int end,int mid){ int iPivit = parition(pArr, begin, end); //符合条件: 中位数位置就是 i=len/3 if (iPivit == mid) { cout << "Find the Median..." << endl; return iPivit; } else if(mid> iPivit) { GetMedianNumber(pArr, iPivit + 1, end,mid); } else { GetMedianNumber(pArr, begin, iPivit-1, mid); } }//非递归方式int GetMedianNumber(int* pArr, int begin, int end){ if (end%2 !=0) { return -1; } int mid = end/ 2; //中位数的位置 int iPivit = 0; while (end >=begin) { iPivit = parition(pArr, begin, end); //符合条件: 中位数位置就是 i=len/2 if (iPivit == mid) { cout << "Find the Median..."<iPivit) { begin = iPivit + 1; parition(pArr, begin, end); } else { end = iPivit - 1; parition(pArr, begin, end); } } return 0;}void test(){ /** int aray[8] = { 2,4, 3, 6,3 ,2,5,5}; //2 0010 int num1 = 0; int num2 = 0; FindNumsAppearOnce(aray, 8, num1, num2); cout << "11=" << num1 << "22=" << num2 << endl; **/ int aray[7] = { 0, 1, 2, 4, 6, 5, 3 }; //int mid = GetMedianNumber(aray,0,6,3); int mid = GetMedianNumber(aray, 0, 6); cout << "mid============" << mid << ":" << aray[mid];}
欢迎关注微信账号 进行讨论