#include <iostream>
using namespace std;
void Swap(int &a,int &b);
int NumOfK(int k,int *a,int start,int end)
{
if (k < start || k > end)
{
return -1;
}
int pos1,pos2;
pos1 = start;
pos2 = end;
int pivotkey = a[start];
while (pos1 < pos2)
{
while ((pos1 < pos2)&&(a[pos2] >= pivotkey))
{
pos2--;
}
Swap(a[pos1],a[pos2]);
while ((pos1 < pos2)&&(a[pos1] <= pivotkey))
{
pos1++;
}
Swap(a[pos1],a[pos2]);
}
if (pos1 == k)
{
return a[k];
}
else if(pos1 > k)
{
return NumOfK(k,a,start,pos1-1);
}
else
{
return NumOfK(k,a,pos1+1,end);
}
}
void Swap(int &a,int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int main(){
int a[]={3,5,8,7,2,6,10};
int num1,num2;
cout<<"Input the first number:";
cin>>num1;
cout<<NumOfK(num1-1,a,0,6)<<endl;
cout<<"Input the second number:";
cin>>num2;
cout<<NumOfK(num2-1,a,num1-1,6)<<endl;
for (int i = num1-1;i < num2;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
system("pause");
return 0;
}
输入的第一个数即为k,第二个数是m,输出结果是第k大的数、第m大的数以及第k到第m大的数