线性选择 求n个数中第k小数
2007-12-23 12:45
197 查看
#include<iostream.h>
#include<time.h>
#include<stdlib.h>
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);
while (a[--i]>x);
if(i>=j)break;
swap(a[i],a[j]);
}
a[p]=a[j];
a[j]=x;
return j;
}
template <class Type>
int randamizedPartition (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 randamizedSelect(Type a[],int p,int r,int k)
{
if (p==r )return a[p];
int i=randamizedPartition(a,p,r);
int j=i-p+1;
if( k<=j) return randamizedSelect(a,p,i,k);
else return randamizedSelect(a,i+1,r,k-j);
}
template<class type> //选择
type select(type a[],int p,int r,int k)
{
if(r-p<75){return a[p+k-a];}
for(int i=0;i<=(r-p-4)/5;i++)
//将a[p+5*i]至a[p+5*i+4]的第三小元素与a[p+i]交换位置;
type x=selexr)a,p,p+(r-p-4)/5,(r-p-4).10;
int i=partition(a,p,r,x),j=i-p+1;
if(k<=j)
return select(a,p,i,k);
else return select(n,i+1,r,k-j);
}
void main()
{
int a[10]={1,2,3,4,5,6,7,8,9,0};
cout<<randamizedSelect(a,0,9,4)<<endl;
}
#include<time.h>
#include<stdlib.h>
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);
while (a[--i]>x);
if(i>=j)break;
swap(a[i],a[j]);
}
a[p]=a[j];
a[j]=x;
return j;
}
template <class Type>
int randamizedPartition (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 randamizedSelect(Type a[],int p,int r,int k)
{
if (p==r )return a[p];
int i=randamizedPartition(a,p,r);
int j=i-p+1;
if( k<=j) return randamizedSelect(a,p,i,k);
else return randamizedSelect(a,i+1,r,k-j);
}
template<class type> //选择
type select(type a[],int p,int r,int k)
{
if(r-p<75){return a[p+k-a];}
for(int i=0;i<=(r-p-4)/5;i++)
//将a[p+5*i]至a[p+5*i+4]的第三小元素与a[p+i]交换位置;
type x=selexr)a,p,p+(r-p-4)/5,(r-p-4).10;
int i=partition(a,p,r,x),j=i-p+1;
if(k<=j)
return select(a,p,i,k);
else return select(n,i+1,r,k-j);
}
void main()
{
int a[10]={1,2,3,4,5,6,7,8,9,0};
cout<<randamizedSelect(a,0,9,4)<<endl;
}
相关文章推荐
- 线性时间选择:从n个元素中找出第k小的元素
- 算法导论标准版快速排序和线性时间求解数组第K小数
- 分治算法:线性时间选择第k大小的数字 && STL函数:nth_element()
- 选择问题:线性时间内找到序列的第k小的元素
- 递归与分治策略之线性选择(第k小元素)
- 中位数之第K小的线性选择算法(续)
- 线性时间选择问题-第k小(大)问题-递归与分治
- 分治算法;随机化划分函数;快速排序;线性时间选择第K小元素;快速排序平均时间复杂度nlgn;
- 中位数之第K小的线性选择算法
- 中位数之第K小的线性选择算法(续)
- 中位数之第K小的线性选择算法
- [置顶] 递归与分治策略-2.9.2线性时间选择(取中位数的中位数基准)(第k小问题)
- 快速选择(quick select) + 线性时间选择(linear-time select) - 求出n个数中第k大的数
- 快速选择(quick select) + 线性时间选择(linear-time select) - 求出n个数中第k大的数
- 线性时间选择第k小(递归)
- 线性选择序列第k小 / 中位数附近k个数
- 递归与分治策略-2.9.1线性时间选择(随机划分基准)(第k小问题)
- 线性时间选择第K小元素(随机化选择第K小元素)C++
- 线性选择算法 .
- 第k小数