期望为线性时间的选择算法randomizedSelect

博客介绍了在期望线性时间复杂度O(n)下,如何实现选择算法randomizedSelect,该算法能有效地解决在数据集中找到特定位置元素的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般选择算法看起来要比找最小值这样的简单问题更难,但有期望为线性时间的选择算法,期望运行时间为O(n)。

#include<iostream>
#include<ctime>
using namespace std;

template<class T> int partition(T *a,int first,int end)   //实现了对子数组A[p..r]的原址重排
{
	int x = a[end-1];
	int i = first-1;
	for(int j=first;j<=end-1;++j)
	{
		if(a[j-1] <= x)
		{
			++i;
			swap(a[i-1],a[j-1]);			
		}
	}
	swap(a[i],a[end-1]);
	return i+1;
}

template<class T>int randomizedPartition(T *a,int first,int end)
{
	 srand((unsigned)time(NULL));  
	int i = rand()%(end-first)+first;

	swap(a[i],a[end-1]);
	return partition(a,first,end);
}


template<class T>T randomizedSelect(T *a,int first,int end,int i)  //返回数组A[first,end]中第i小的元素
{
	if(first == end)
		return a[first-1];
	int q = randomizedPartition(a,first,end);
	int k = q-first+1;
	if(i==k)             // the pivot value is the answer
		retur
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值