题目连接:https://pintia.cn/problem-sets/14/problems/743
直接附代码(C语言):
//类似快速排序,找到flag元素,小的放在前面,大的放在后面
int getIndex(ElementType arr[], int low, int high) {
float tmp = arr[low];
while (low < high) {
while (low < high && arr[high] >= tmp) {
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= tmp) {
low++;
}
arr[high] = arr[low];
}
arr[low] = tmp;
return low;
}
// arr数组中 区间[s,e]查找第x大的元素
float findN(ElementType arr[], int s, int e, int x){
int a = getIndex(arr, s, e);
int l = a - s;
int r = e - a;
if(x == l+1){
return arr[a];
} else if(x<=l) {
return findN(arr,s,a-1,x);
} else if (x>l+1) {
return findN(arr,a+1,e,x-l-1);
}
}
float Median(ElementType A[], int N){
return findN(A,0,N-1,N/2+1);
}