当前位置:文档之家› 线性时间选择算法

线性时间选择算法

福州大学数学与计算机科学学院
《计算机算法设计与分析》上机实验报告(1)
图中箭头指向表示大的数值指向小的数值,所以根据图
可以看出,在x的右边,每一个包含5个元素的组中至少有3
个元素大于x,在x的左边,每一组中至少有3个元素小于x (保证x分割一边必定有元素存在)。

图中显示的中位数的中位数x的位置,每次选取x作为划
分的好处是能够保证必定有一部分在x的一边。

所以算法最坏
情况的递归公式可以写成:
,使用替换法可以得出)
(。

T
n
cn
4、算法代码:
#include <iostream>
#include <ctime>
using namespace std;
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()
{
void SelectionSort(int a[]);
int s;
int a[2000];
int b[2000];
for(int i=0; i<2000; i++)
{
a[i]=b[i]=rand()%10000;
cout<<a[i]<<" ";
}
cout<<endl;
SelectionSort(b);
for(int j=0;j<2000;j++)
{
printf("a[%d]:%d ",j+1,b[j]);
}
cout<<endl;
printf("请输入要求的第几最小数:");
scanf("%d",&s);
cout<<RandomizedSelect(a,0,1999,s)<<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 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);
}
}
void SelectionSort(int a[])
{
int min;
for (int i = 0; i < 2000 - 1; i++)
{
min = i;
for (int j = i + 1; j < 2000; j++)
{
if (a[j] < a[min])
min = j;
}
int t = a[min];
a[min] = a[i];
a[i] = t;
}
return ;
}
实验结果截图:
实验结果。

相关主题