c语言分治法线性时间选择,分治法~线性时间选择.doc

分治法~线性时间选择

《计算机算法设计与分析》实 验 报 告

实验名称:线性时间选择问题实验地点:所使用的开发工具及环境:实验目的:

熟悉掌握分治算法设计技术二、实验内容:

1、按教材所授内容要求,完成“线性时间选择问题”算法。得到一个完整正确的程序。

2、问题规模:不少于2000

3、输出最终结果。

基本思想、原理和算法描述:

基本思想:将n个输入元素划分成┌ n/5┐个组,每组有5个元素,除最后一组可能不是5个元素之外用任意一种算法,将每组的元素排好序,并取出每组的中位数,共┌ n/5┐个。调用Select找出这┌ n/5┐个元素的中位数,如果┌ n/5┐是偶数就找两个中位数中较大的一个。在这里我用的排序的方法是快速排序。

算法描述:

template

Type Select(Type a[],int p,int r,int k)

{int i;

if(r-p<75)

{

Qsort(a,p,r);

return a[p+k-1];

}

//(r-p-4)/5相当于n-5

for(i=0; i<=(r-p-4)/5; i++)

{

//将元素每5个分成一组,分别排序,并将该组中位数与a[p+i]交换位置

//使所有中位数都排列在数组最左侧,以便进一步查找中位数的中位数

Qsort(a,p+5*i,p+5*i+4);

Swap(a[p+5*i+2],a[p+i]);

}

//找中位数的中位数

Type x = Select(a,p,p+(r-p-4)/5,(r-p-4)/10);

i = Partition(a,p,r,x);

int j = i-p+1;

if(k<=j)

{

return Select(a,p,i,k);

}

else

{

return Select(a,i+1,r,k-j);

}

}源程序清单:

#include

#include

#include

#include

#include

template

void Swap(Type &x,Type &y);

inline int Random(int x, int y);

template

void Qsort(Type a[] ,int p,int r);

template

int Partition(Type a[],int p,int r,Type x);

template

Type Select(Type a[],int p,int r,int k);

void main()

{

int a[2000];

srand((unsigned)time(NULL));

for(int i=0; i<2000; i++)

{

a[i] = Random(0,2000);

cout<

}

cout<

cout<

//重新排序,对比结果

Qsort(a,0,1999);

for( i=0; i<2000; i++)

{

cout<

}

cout<

}

template

void Swap(Type &x,Type &y)

{

Type temp = x;

x = y;

y = temp;

}

inline int Random(int x, int y)

{

int ran_num = rand() % (y - x) + x;

return ran_num;

}

template

void Qsort(Type a[] ,int p,int r)

{

if(p

{

Type x;

int q=Partition(a,p,r,x);

Qsort(a,p,q-1);

Qsort(a,q+1,r);

}

}

template

int Partition(Type a[],int p,int r,Type x)

{

int i = p;

int j = r + 1;

x=a[p];

while(true

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值