大家看后给个最好的方法啊,这个只是使用了冒泡排序的方法加以改进的。
#include<iostream>
using namespace std;
//求第K最大值
//想法是用冒泡排序的方法,很大的缺点是改变了原来的数组的顺序
int QueryKMax( int a[], int len, int k)
{
int count = 0;
int temp = 0;
bool endcir = true;
for(int i = 0; (i<len)&&(count<=k)&&endcir;i++ )
{
endcir = false;
for( int j =0; j<len-i;j++)
{
if(a[j]>a[j+1] )
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
endcir = true;
}
}
count++;
}
return a[len-count+1];
}
void main()
{
int arr[10] = {8,45,9,4,2,5,26,2,10,23};
int len = 10;
int k = 4;
cout<< " the K max value is " << QueryKMax(arr, len, k ) <<endl;
for(int i = 0; i<len; i++ )
{
cout<<arr[i]<< " ";
}
}