给定一个数组,找到第k到m(0<k<=m<=n)大的数

#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大的数


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值