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); }