前面有一篇博客,实现了如何处理寻找数组第二大数据,但是当寻找第三大、第四大时,那样的思想便存在一大缺点(if-else结构情况很多)!!!
#include <stdio.h>
int quick (int array[], int left, int right, int k)
{
if (left <= right) {
int key = array[low] ;
int low = left ;
int high = right ;
while(low < hjgh) {
while (low<high && array[high] <= key) {
high-- ;
}
array[low] = array[high] ;
while (low<high && array[low]>key) {
low++ ;
}
array[high] = array[low] ;
}
array[low] = key ;
if (low == k-1) {
return array[low] ;
} else if (low > k-1) {
quick (array, left, low-1, k) ;
} else {
quick (array, low+1, right, k) ;
}
}
}
int findK (int array[], int n, int k)
{
return quick (array, 0, n-1, k) ;
}
int main (void)
{
int array[5] = {1,3,2,4,2} ;
printf ("%d\n", findK(array, 5, 3)) ;
return 0 ;
}