题解 | #寻找第K大#
寻找第K大
http://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf
*
* @param a int整型一维数组
* @param aLen int a数组长度
* @param n int整型
* @param K int整型
* @return int整型
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
int partition(int* a, int low, int high){
int p = a[low];
while(low < high){
while(low < high && a[high] <= p)high--;
a[low] = a[high];
while(low < high && a[low] >= p)low++;
a[high] = a[low];
}
a[low] = p;
return low;
}
int quicksort(int* a, int low, int high, int K){
int p;
if(low < high){
p = partition(a, low, high);
if(p == K){
return p;
}else if(p < K){
quicksort(a, p+1, high, K);
}else{
quicksort(a, low, p-1, K);
}
}
return p;
}
int findKth(int* a, int aLen, int n, int K ) {
// write code here
quicksort(a, 0, aLen-1, K-1);
return a[K-1];
}