第i小元素

在一个含有n个不同数的集合中找到第i小的元素。

利用分治的思想,算法的平均时间为O(n)

#include <time.h>
#include <iostream>
using namespace std;

int Partition(int A[],int p,int r)
{
	int x=A[r],i=p-1,j,temp;
	for(j=p;j<r;j++)
	{
		if(A[j]<=x)
		{
			i++;
			temp=A[j];
			A[j]=A[i];
			A[i]=temp;
		}
	}
	temp=A[r];
	A[r]=A[i+1];
	A[i+1]=temp;
	return i+1;
}

int Random_Partition(int A[],int p,int r)
{
	srand((unsigned int)time(0));
	int i=(rand()%(r-p+1))+p;  //get the random num from[p,r]
	int temp=A[r];
	A[r]=A[i];
	A[i]=temp;
	return Partition(A,p,r);
}

//利用快排分治的思想,进行划分求解数组中的第i小元素
int Random_Select(int A[],int p,int r,int i)
{
	//return the ith min num int the A[]
	if(p == r)
		return A[p];
	int q=Random_Partition(A,p,r);
	int k=q-p+1;
	if(i == k)
		return A[q];
	else if(i < k)
		return Random_Select(A,p,q-1,i);
	else
		return Random_Select(A,q+1,r,i-k);
}

int main()
{
	int A[9]={12,5,21,6,32,8,11,9,14};
	int i,p,j;
	cout<<"输入一个整数,求数组中的第i小元素,输入0结束"<<endl;
	while(cin>>i)
	{
		if(i == 0)
			break;
		else if(i>9)
			cout<<"数组元素个数少于 "<<i<<endl;
		else
		{
			p=Random_Select(A,0,8,i);
			for(j=0;j<9;j++)
				cout<<A[j]<<"  ";
			cout<<endl;
			cout<<"数组中的第 "<<i<<" 小元素是:"<<p<<endl;
		}
	}
	return 0;
}

运行结果

输入一个整数,求数组中的第i小元素,输入0结束
3
5  6  8  9  11  21  12  14  32
数组中的第 3 小元素是:8
6
5  6  8  9  11  12  14  32  21
数组中的第 6 小元素是:12
0
Press any key to continue


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值