参考下面的程序,输入输出就你自己修改了,不然等于帮你做作业了。
#include<iostream>
#include<stdio.h>
using namespace std;
int Partition (int *L, int low, int high)
{
int temp = L[low];
int pt = L[low]; //哨兵
while (low != high)
{
while (low < high && L[high] >= pt)
high--;
L[low] = L[high];
while (low < high && L[low] <= pt)
low++;
L[high] = L[low];
}
L[low] = temp;
return low;
}
void QSort (int *L, int low, int high) //快速排序
{
int pl;
if (low < high)
{
pl = Partition (L,low,high);
QSort (L, low, pl-1);
QSort (L, pl+1, high);
}
}
void findk(int k,int *L,int low,int high)
{
int temp;
temp=Partition(L,low,high);
if(temp==k-1)
{
cout<<"第"<<temp+1<<"大的数是:"<<L[temp]<<endl;
}
else if(temp>k-1)
findk(k,L,low,temp-1);
else
findk(k,L,temp+1,high);
}
int main()
{
int a[10]={15,25,9,48,36,100,58,99,126,5},i,j,k;
cout<<"排序前:"<<endl;
for(i=0;i<10;i++){
cout<<a[i]<<" ";
}
cout<<endl;
cout<<"请输入你要查找第k大的数:"<<endl;
cin>>k;
findk(k,a,0,9); //查找第k大的数不需要全部排序
QSort(a,0,9);
cout<<"排序后:"<<endl;
for(i=0;i<10;i++){
cout<<a[i]<<" ";
}
cout<<endl;
system("Pause");
return 0;
}