0006算法笔记——【分治法】线性时间选择

本文介绍了线性时间选择问题的解决方法,包括随机划分法和利用中位数的选择算法。随机划分法平均时间复杂度为O(n),最坏情况为O(n^2)。利用中位数的算法确保在最坏情况下仍保持线性时间复杂度,通过分组、取中位数并递归划分来找到第k小的元素。

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

          线性时间选择问题:给定线性序集中n个元素和一个整数k,1≤k≤n,要求找出这n个元素中第k小的元素,(这里给定的线性集是无序的)。

       1、随机划分线性选择

       线性时间选择随机划分法可以模仿随机化快速排序算法设计。基本思想是对输入数组进行递归划分,与快速排序不同的是,它只对划分出的子数组之一进行递归处理

       程序清单如下:

//2d9-1 随机划分线性时间选择
#include "stdafx.h"
#include <iostream> 
#include <ctime>
using namespace std; 

int a[] = {5,7,3,4,8,6,9,1,2};

template <class Type>
void Swap(Type &x,Type &y);

inline int Random(int x, int y);

template <class Type>
int Partition(Type a[],int p,int r);

template<class Type>
int RandomizedPartition(Type a[],int p,int r);

template <class Type>
Type RandomizedSelect(Type a[],int p,int r,int k);

int main()
{
	for(int i=0; i<9; i++)
	{
		cout<<a[i]<<" ";
	}
	cout<<endl;
	cout<<RandomizedSelect(a,0,8,3)<<endl;
}

template <class Type>
void Swap(Type &x,Type &y)
{
	Type temp = x;
	x = y;
	y = temp;
}

inline int Random(int x, int y)
{
     srand((unsigned)time(0));
     int ran_num = rand() % (y - x) + x;
     return ran_num;
}

template <class Type>
int Partition(Type a[],int p,int r)
{
	int i = p,j = r + 1;
	Type x = a[p];

	while(true)
	{
		while(a[++i]<x && i<r);
		while(a[--j]>x);
		if(i>=j)
		{
			break;
		}
		Swap(a[i],a[j]);
	}
	a[p] = a[j];
	a[j] = x;
	return j;
}

template<class Type>
int RandomizedPartition(Type a[],int p,int r)
{
	int i = Random(p,r);
	Swap(a[i],a[p]);
	return
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值