算法分析及设计实验报告

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

算法分析与设计

专业班级:

姓名:

学号:

指导老师:

实验一递归算法的设计与实现

•计算整数的非负整数次幂

(1)设计思路

对于34按步骤可以分析:

34=32*32

32=31*31

31=31*1

对于33按步骤可以分析:

33=32*31;

32=31*31;

31=31*1;

分析可以得到:

当x n中n为奇数时,x n=x*(x n/2)2

当x n中n为偶数的,x n=(x n/2)2;

当n/2=0;return 1;

一步步进行递归返回计算,如果n位奇数,在进行一部乘以x 否则返回运算结果

(2)源程序代码

#include

using namespace std;

int power(int x,int n)

{

int y;

if(n==0)

{

y=1;

}

else

{

y=power(x,n/2);

y=y*y;

if(n%2==1)

{

y=y*x;

}

}

return y;

}

void main()

{

cout<<"请输入一个底数X:";

int x;

cin>>x;

cout<<"请输入一个指数Y: ";

int y;

cin>>y;

if(y<0)

{

cout<<"你的输入有误:请重新输入:"<

cin>>y;

}

int c;

c=power(x,y);

cout<

(3)代码运行结果

(4)时间复杂度

令n=2k,则可以得到:f(n)=g(k)=k+1=logn+1=O(logn)

2.基于递归算法的插入排序

(1)设计思路

通过主函数传来一个数组的首地址和数组的长度,然后利用递归的原理,当n=0;程序返回,执行入栈的递归程序,依次比较2个数的大小,3个数的大小等,根据比较的结果将第n个数插入适当的位置。

(2)源程序代码

#include

using namespace std;

void insert (int a[],int n)

{

int k;

int b;

n=n-1;

if(n>0)

{

insert(a,n);

b=a[n];

k=n-1;

while((k>=0)&&(a[k]>b))

{

a[k+1]=a[k];

k=k-1;

}

a[k+1]=b;

}

}

void main()

{

int a[100];

int n;

cout<<"请输入数组A[]的元素个数n(1

cin>>n;

cout<<"请输入数组A[]的元素: ";

for(int i=0;i

{

cin>>a[i];

}

insert(a,n);

for(int j=0;j

{

cout<

}

cout<

}

(3)代码运行结果

(4)时间复杂度

f(n)=f(n-1)+n-1=f(n-2)+n-1+(n+2)=n*(n-1)/2;

算法用于递归栈的工作单元数与n为同一数量级,即时间复杂度为O(n)

实验二递归算法的实现

•自然归并算法的设计与实现

•设计思路

首先讲待排序的n个元素分成大致相同的子集合,然后分别对这两个子集进行排序最后将排好序的子集合归并成所要求的排好序的集合

•源程序代码

#include

#include

using namespace std;

#define max 10

void Merger_Sort(int a[],int low,int high) {

int temp[max];

if(low

{

int mid=(low+high)/2;

int i=low;

int j=mid+1;

int l=low;

Merger_Sort(a,low,mid);

Merger_Sort(a,mid+1,high);

while(i<=mid&&j<=high)

{

if(a[i]

{

temp[l++]=a[i++];

}

else

{

temp[l++]=a[j++];

}

}

while(i<=mid)

{

temp[l++]=a[i++];

}

while(j<=high)

{

temp[l++]=a[j++];

}

for(i=low;i<=high;i++)

{

a[i]=temp[i];

}

}

}

void main()

{

int a[max];

int n;

相关文档
最新文档