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

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

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
0006算法笔记——【分治法】线性时间选择分析重点

?线性时间选择问题:给定线性序集中n个元素和一个整数k,1≤k≤n,要求找出这n个元素中第k小的元素,(这里给定的线性集是无序的)。? ? ? ?1、随机划分线性选择? ? ? ?线性时间选择随机划分法可以模仿随机化快速排序算法设计。基本思想是对输入数组进行递归划分,与快速排序不同的是,它只对划分出的子数组之一进行递归处理。? ? ? ?程序清单如下:[cpp]?view plain?copy//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);????templateclass?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;?i9;?i++)??????{??????????couta[i]?;??????}??????coutendl;??????coutRandomizedSelect(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??ir);??????????while(a[--j]x);??????????if(i=j)??????????{??????????????break;??????????}??????????Swap(a[i],a[j]);??????}??????a[p]?=?a[j];??????a[j]?=?x;??????return?j;??}????templateclass?Type??int?RandomizedPartition(Type?a[],int?p,int?r)??{??????int?i?=?Random(p,r);??????Swap(a[i],a[p]);??????return?Partition(a,p,r);??}????template?class?Type??Type?RandomizedSelect(Type?a[],int?p,int?r,int?k)??{??????if(p?==?r)??????{??????????return?a[p];??????}??????int?i?=?RandomizedPartition(a,p,r);??????int?j?=?i?-?p?+?1;??????if(k?=?j)??????{??????????return?RandomizedSelect(a,p,i,k);??????}??????else??????{??????????//由于已知道子数组a[p:i]中的元素均小于要找的第k小元素??????????//因此,要找的a[p:r]中第k小元素是a[i+1:r]中第k-j小元素。??????????return?RandomizedSelect(a,i+1,r,k-j);??????}??}??? ? ? ?程序解释:利用随机函数产生划分基准,将数组a[p:r]划分成两个子数组a[p:i]和a[i+1:r],使a[p:i]中的每个元素都不大于a[i+1:r]中的每个元素

文档评论(0)

dajuhyy + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档