算法与数据结构C语言习题参考答案-9章

合集下载

算法数数据结构 第3版 绪论课后答案

算法数数据结构 第3版 绪论课后答案

算法与数据结构---C语言描述(第三版)第1章绪论1、解释以下概念:逻辑结构,存储结构,操作,数据结构,数据结构的表示,数据结构的实现,抽象数据类型,算法,算法的时间代价,算法的空间代价,大O表示法,贪心法,回溯法,分治法。

答:(1)逻辑结构(数学模型):①指数据元素之间地逻辑关系。

②具体解释:指数学模型(集合,表,树,和图)之间的关系。

③描述方式:B = <K,R>, K是节点的有穷集合,R是K上的一个关系。

(2)存储结构(物理结构):数据的逻辑结构在计算机存储器中的映射(或表示)。

(3) 操作(行为):指抽象数据类型关心的的各种行为在不同的存储结构上的具体算法(或程序)。

(4) 数据结构:①传统观念:数据结构是计算机中表示(存储)的、具有一定逻辑关系和行为特征的一组数据。

②根据面向对象的观点:数据结构是抽象数据类型的物理实现。

(5) 数据结构的表示:(6) 数据结构的实现:(7) 抽象数据类型:(8) 算法:是由有穷规则构成(为解决某一类问题)的运算序列。

-算法可以有若干输入(初始值或条件)。

-算法通常又有若干个输出(计算结果)。

-算法应该具有有穷性。

一个算法必须在执行了有穷步之后结束。

-算法应该具有确定性。

算法的每一步,必须有确切的定义。

-算法应该有可行性。

算法中国的每个动作,原则上都是能够有机器或人准确完成的。

(9) 算法的时间代价:(10) 算法的空间代价:(11) 大O表示法:-更关注算法复杂性的量级。

-若存在正常数c和n0,当问题的规模n>=c*f(n), 则说改算法的时间(或空间)代价为O(f(n))(12) 贪心法:当追求的目标是一个问题的最优解是,设法把整个问题的求解工作分成若干步来完成。

在其中的每一个阶段都选择都选择从局部来看是最优的方案,以期望通过各个阶段的局部最有选择达到整体的最优。

例如:着色问题:先用一种颜色尽可能多的节点上色,然后用另一种颜色在为着色节点中尽可能多的节点上色,如此反复直到所有节点都着色为止;(13) 回溯法有一些问题,需要通过彻底搜索所有的情况寻找一个满足某些预定条件的最优解。

数据结构(C语言版)9-12章练习 答案 清华大学出版社

数据结构(C语言版)9-12章练习 答案 清华大学出版社

数据结构(C语言版)9-12章练习答案清华大学出版社9-12章数据结构作业答案第九章查找选择题1、对n个元素的表做顺序查找时,若查找每个元素的概率相同,则平均查找长度为( A )A.(n+1)/2 B. n/2 C. n D. [(1+n)*n ]/2 2. 下面关于二分查找的叙述正确的是 ( D )A. 表必须有序,表可以顺序方式存储,也可以链表方式存储B. 表必须有序且表中数据必须是整型,实型或字符型 C. 表必须有序,而且只能从小到大排列 D. 表必须有序,且表只能以顺序方式存储3. 二叉查找树的查找效率与二叉树的( (1)C)有关, 在 ((2)C )时其查找效率最低 (1): A. 高度 B. 结点的多少 C. 树型 D. 结点的位置(2): A. 结点太多 B. 完全二叉树 C. 呈单枝树 D. 结点太复杂。

4. 若采用链地址法构造散列表,散列函数为H(key)=key MOD 17,则需 ((1)A)个链表。

这些链的链首指针构成一个指针数组,数组的下标范围为 ((2)C) (1) A.17 B. 13 C. 16 D. 任意(2) A.0至17 B. 1至17 C. 0至16 D. 1至16判断题1.Hash表的平均查找长度与处理冲突的方法无关。

(错) 2. 若散列表的负载因子α<1,则可避免碰撞的产生。

(错)3. 就平均查找长度而言,分块查找最小,折半查找次之,顺序查找最大。

(错)填空题1. 在顺序表(8,11,15,19,25,26,30,33,42,48,50)中,用二分(折半)法查找关键码值20,需做的关键码比较次数为 4 .算法应用题1. 设有一组关键字{9,01,23,14,55,20,84,27},采用哈希函数:H(key)=key mod7 ,表长为10,用开放地址法的二次探测再散列方法Hi=(H(key)+di) mod 10解决冲突。

要求:对该关键字序列构造哈希表,并计算查找成功的平均查找长度。

数据结构第三版第九章课后习题参考答案

数据结构第三版第九章课后习题参考答案

}
}
设计如下主函数:
void main()
{ BSTNode *bt;
KeyType k=3;
int a[]={5,2,1,6,7,4,8,3,9},n=9;
bt=CreatBST(a,n);
//创建《教程》中图 9.4(a)所示的二叉排序树
printf("BST:");DispBST(bt);printf("\n");
#define M 26 int H(char *s)
//求字符串 s 的哈希函数值
{
return(*s%M);
}
构造哈希表 void Hash(char *s[]) //
{ int i,j;
char HT[M][10]; for (i=0;i<M;i++)
//哈希表置初值
HT[i][0]='\0'; for (i=0;i<N;i++) { j=H(s[i]);
//求每个关键字的位置 求 // s[i]的哈希函数值
while (1)
不冲突时 直接放到该处 { if (HT[j][0]=='\0') //
,
{ strcpy(HT[j],s[i]);
break;
}
else
//冲突时,采用线性线性探测法求下一个地址
j=(j+1)%M;
}
} for (i=0;i<M;i++)
printf("%2d",path[j]);
printf("\n");
}
else { path[i+1]=bt->key;

数据结构(C语言版清华大学出版社)8-9章课后部分答案

数据结构(C语言版清华大学出版社)8-9章课后部分答案

第八章选择题1.C2.A3.B4.C5.D6.B7.B8.A9.D 10.D 11.C 12.C填空题1. n、n+12. 43. 8.25( 折半查找所在块 )4. 左子树、右子树5. 266. 顺序、(n+1)/2、O(log2n)7. m-1、[m/2]-18. 直接定址应用题1. 进行折半查找时,判定树是唯一的,折半查找过程是走了一条从根节点到末端节点的路径,所以其最大查找长度为判定树深度[log2n]+1.其平均查找长度约为[log2n+1]-1.在二叉排序树上查找时,其最大查找长度也是与二叉树的深度相关,但是含有n个节点的二叉排序树不是唯一的,当对n个元素的有序序列构造一棵二叉排序树时,得到的二叉排序树的深度也为n,在该二叉树上查找就演变成顺序查找,此时的最大查找长度为n;在随机情况下二叉排序树的平均查找长度为1+4log2n。

因此就查找效率而言,二分查找的效率优于二叉排序树查找,但是二叉排序树便于插入和删除,在该方面性能更优。

3. 评价哈希函数优劣的因素有:能否将关键字均匀的映射到哈希表中,有无好的处理冲突的方法,哈希函数的计算是否简单等。

冲突的概念:若两个不同的关键字Ki和Kj,其对应的哈希地址Hash(Ki) = Hash(Kj),则称为地址冲突,称Ki和K,j为同义词。

(1)开放定址法(2)重哈希法(3)链接地址法4.(1)构造的二叉排序树,如图(2)中序遍历结果如下:10 12 15 20 24 28 30 35 46 50 55 68(4)平均查找长度如下:ASLsucc = (1x1+2x2+3x3+4x3+5x3)/12 = 41/128.哈希地址如下:H(35) = 35%11 = 2H(67) = 67%11 = 1H(42) = 42%11 = 9H(21) = 21%11 = 10H(29) = 29%11 = 7H(86) = 86%11 = 9H(95) = 95%11 = 7H(47) = 47%11 = 3H(50) = 50%11 = 6H(36) = 36%11 = 3H(91) = 91%11 = 3第九章选择题1.D2.C3.B4.D5.C6.B7.A8.A9.D 10.D填空题1. 插入排序、交换排序、选择排序、归并排序2. 移动(或者交换)3. 归并排序、快速排序、堆排序4. 保存当前要插入的记录,可以省去在查找插入位置时的对是否出界的判断5. O(n)、O(log2n)6. 直接插入排序或者改进了的冒泡排序、快速排序7. Log2n、n8. 完全二叉树、n/29. 1510. {12 38 25 35 50 74 63 90}应用题2.(1)Shell排序(步长为5 3 1)每趟的排序结果初始序列为100 87 52 61 27 170 37 45 61 118 14 88 32步长为5的排序14 37 32 61 27 100 87 45 61 118 170 88 52步长为3的排序结果14 27 32 52 37 61 61 45 88 87 170 100 118步长为1的排序结果14 27 32 37 45 52 61 61 87 88 100 118最后结果14 27 32 37 45 52 61 61 87 88 100 118 170(2)快速排序每趟的排序结果如图初始序列100 87 52 61 27 170 37 45 61 118 14 88 32第一趟排序[32 87 52 61 27 88 37 45 61 14]100[118 170]第二趟排序[14 27]32[61 52 88 37 45 61 87]100 118[170]第三趟排序14[27]32[45 52 37]61[88 61 87]100 118[170]第四趟排序14[27]32[37]45[52]61[87 61]88 100 118[170]第五趟排序14[27]32[37]45[52]61[87 61]88 100 118[170]最后结果14[27]32[37]45[52]61[61]87 88 100 118[170](3)二路归并排序每趟的排序结果初始序列[100][87][52][61][27][170][37][45][61][118][14][88][32]第一趟归并[87 100][52 61][27 170][37 45][61 118][14 88][32]第二趟归并[52 61 87 100][27 37 45 170][14 61 88 118][32]第三趟归并排序[27 37 45 52 61 87 100 170][14 32 61 88 118]第四趟归并排序[14 27 32 37 45 52 61 61 87 88 100 118 170]最后结果14 27 32 37 45 52 61 61 87 88 100 118 1705. 采用快速排序时,第一趟排序过程中的数据移动如图:算法设计题1.分析:为讨论方便,待排序记录的定义为(后面各算法都采用此定义):#define MAXSIZE 100 /* 顺序表的最大长度,假定顺序表的长度为100 */ typedef int KeyType; /* 假定关键字类型为整数类型 */typedef struct {KeyType key; /* 关键字项 */OtherType other; /* 其他项 */}DataType; /* 数据元素类型 */typedef struct {DataType R[MAXSIZE+1]; /* R[0]闲置或者充当哨站 */int length; /* 顺序表长度 */}sqList; /* 顺序表类型 */设n个整数存储在R[1..n]中,因为前n-2个元素有序,若采用直接插入算法,共要比较和移动n-2次,如果最后两个元素做一个批处理,那么比较次数和移动次数将大大减小。

数据结构C语言版部分习题及答案

数据结构C语言版部分习题及答案

国家计算机等级考试二级C语言公共基础知识总结第一章数据结构与算法1.1 算法算法:是指解题方案的准确而完整的描述。

算法不等于程序,也不等计算机方法,程序的编制不可能优于算法的设计。

算法的基本特征:是一组严谨地定义运算顺序的规则,每一个规则都是有效的,是明确的,此顺序将在有限的次数下终止。

特征包括:(1)可行性;(2)确定性,算法中每一步骤都必须有明确定义,不充许有模棱两可的解释,不允许有多义性;(3)有穷性,算法必须能在有限的时间内做完,即能在执行有限个步骤后终止,包括合理的执行时间的含义;(4)拥有足够的情报。

算法的基本要素:一是对数据对象的运算和操作;二是算法的控制结构。

指令系统:一个计算机系统能执行的所有指令的集合。

基本运算包括:算术运算、逻辑运算、关系运算、数据传输。

算法的控制结构:顺序结构、选择结构、循环结构。

算法基本设计方法:列举法、归纳法、递推、递归、减斗递推技术、回溯法。

算法复杂度:算法时间复杂度和算法空间复杂度。

算法时间复杂度是指执行算法所需要的计算工作量。

算法空间复杂度是指执行这个算法所需要的内存空间。

1.2 数据结构的基本基本概念数据结构研究的三个方面:(1)数据集合中各数据元素之间所固有的逻辑关系,即数据的逻辑结构;(2)在对数据进行处理时,各数据元素在计算机中的存储关系,即数据的存储结构;(3)对各种数据结构进行的运算。

数据结构是指相互有关联的数据元素的集合。

数据的逻辑结构包含:(1)表示数据元素的信息;(2)表示各数据元素之间的前后件关系。

数据的存储结构有顺序、链接、索引等。

线性结构条件:(1)有且只有一个根结点;(2)每一个结点最多有一个前件,也最多有一个后件。

非线性结构:不满足线性结构条件的数据结构。

1.3 线性表及其顺序存储结构线性表是由一组数据元素构成,数据元素的位置只取决于自己的序号,元素之间的相对位置是线性的。

在复杂线性表中,由若干项数据元素组成的数据元素称为记录,而由多个记录构成的线性表又称为文件。

数据结构(C语言版)习题及答案第九章

数据结构(C语言版)习题及答案第九章

数据结构(C语言版)习题及答案第九章数据结构(C语言版)习题及答案习题一、选择题1、一组记录的排序码为〔46,79,56,38,40,84〕,那么利用堆排序的方法建立的初始堆为( B )。

A、79,46,56,38,40,80B、84,79,56,38,40,46C、84,79,56,46,40,38D、84,56,79,40,46,382、排序趟数与序列原始状态(原始排列)有关的排序方法是〔 ACD 〕方法。

A、插入排序B、选择排序C、冒泡排序D、快速排序3 、以下排序方法中,〔 B 〕是稳定的排序方法。

A、直接选择排序B、二分法插入排序C、希尔排序D、快速排序4、数据序列〔8,9,10,4,5,6,20,1,2〕只能是以下排序算法中( C )的两趟排序后的结果。

A、选择排序B、冒泡排序C、插入排序D、堆排序5、对序列(15,9,7,8,20,-1,4)进行排序,进行一趟排序后,数据的排列变为〔4,9,-1,8,20,7,15〕,那么采用的是〔 C 〕排序。

A、选择B、快速C、希尔D、冒泡6 、一组待排序记录的关键字为〔46,79,56,38,40,84〕,那么利用快速排序,以第一个记录为基准元素得到的一次划分结果为〔 C 〕。

A、(38,40,46,56,79,84)B、(40,38,46,79,56,84)C、(40,38,46,56,79,84)D、(40,38,46,84,56,79)7、用直接插入排序对下面四个序列进行排序〔由小到大〕,元素比拟次数最少的是〔 C 〕。

A、94,32,40,90,80,46,21,69B、32,40,21,46,69,94,90,80C、21,32,46,40,80,69,90,94D、90,69,80,46,21,32,94,408、假设用冒泡排序对关键字序列〔18,16,14,12,10,8〕进行从小到大的排序,所需进行的关键字比拟总次数是〔 B 〕。

《数据结构、算法与应用(C++语言描述)》习题参考答案doc

《数据结构、算法与应用(C++语言描述)》习题参考答案doc
2.如何实现线性表的顺序存储结构? 把线性表的结点按逻辑顺序依次存放在一组地址连续的存储单元里就构成了线性表的
顺序存储,采用顺序存储结构的线性表简称顺序表。线性表的顺序存储结构有如下特点: 线性表中所有元素所占的存储空间是连续的; 线性表的逻辑顺序与物理顺序一致; 数组中的每一个元素的位置可以用公式来确定。假设线性表中的第一个数据元素 的存储地址(指第一个字节的地址,即首地址)为 LOC(e1),每一个数据元素占 k 个字节,则线性表中第 i 个元素 ei 在计算机存储空间中的存储地址为: LOC(ei)=LOC(e1)+(i-1)k
单向链表:在线性链表中,用一个专门的指针指向线性表中第一个结点,每一个结点 的指针都指向它的下一个逻辑结点,线性链表的最后一个结点的指针为空(用 NULL 或 0 表示),表示链表终止,这样的线性链表称为单向链表。下图是单向链表示意图。
first
e1
e2

ei
… 线性表的单向链式存储

en

NULLNULL
5.请列举出一些线性表问题的实例。 ①按员工号排序的员工基本情况表; ②奥运会各项比赛日程; ③按学号记录的学生的成绩单; 等等。
6. 对于顺序表和单向链表,如何实现统计重复元素个数的操作?
在顺序表中实现统计重复元素个数的操作: 在教材的【描述 2-1】中,增加一个统计重复元素个数的成员函数:
int Count(const T&x); //返回 x 出现的次数 在教材的【描述 2-2】中,增加查找重复元素个数的成员函数的实现: //实现统计重复元素个数 template<class T> int LinearList<T>::Count(const T& x) {

中南大学数据结构与算法第9章查找课后作业答案

中南大学数据结构与算法第9章查找课后作业答案

第9章查找习题练习答案1.对含有n个互不相同元素的集合,同时找最大元和最小元至少需进行多少次比较?答:设变量max和min用于存放最大元和最小元(的位置),第一次取两个元素进行比较,大的放入max,小的放入min。

从第2次开始,每次取一个元素先和max比较,如果大于max 则以它替换max,并结束本次比较;若小于max则再与min相比较,在最好的情况下,一路比较下去都不用和min相比较,所以这种情况下,至少要进行n-1次比较就能找到最大元和最小元。

2.若对具有n个元素的有序的顺序表和无序的顺序表分别进行顺序查找,试在下述两种情况下分别讨论两者在等概率时的平均查找长度:(1)查找不成功,即表中无关键字等于给定值K的记录;(2)查找成功,即表中有关键字等于给定值K的记录。

答:查找不成功时,需进行n+1次比较才能确定查找失败。

因此平均查找长度为n+1,这时有序表和无序表是一样的。

查找成功时,平均查找长度为(n+1)/2,有序表和无序表也是一样的。

因为顺序查找与表的初始序列状态无关。

3.画出对长度为18的有序的顺序表进行二分查找的判定树,并指出在等概率时查找成功的平均查找长度,以及查找失败时所需的最多的关键字比较次数。

答:等概率情况下,查找成功的平均查找长度为:ASL=(1+2*2+3*4+4*8+5*3)/18=3.556查找失败时,最多的关键字比较次树不超过判定树的深度,此处为5.4.为什么有序的单链表不能进行折半查找?答:因为链表无法进行随机访问,如果要访问链表的中间结点,就必须先从头结点开始进行依次访问,这就要浪费很多时间,还不如进行顺序查找,而且,用链存储结构将无法判定二分的过程是否结束,因此无法用链表实现二分查找。

5.设有序表为(a,b,c,e,f,g,i,j,k,p,q),请分别画出对给定值b,g和n进行折半查找的过程。

解:(1)查找b的过程如下(其中方括号表示当前查找区间,圆括号表示当前比较的关键字)下标: 1 2 3 4 5 6 7 8 9 10 11 12 13第一次比较: [a b c d e f (g) h i j k p q]第二次比较: [a b (c) d e f] g h i j k p q第三次比较: [a (b)]c d e f g h i j k p q经过三次比较,查找成功。

严蔚敏《数据结构(c语言版)习题集》算法设计题第九章答案

严蔚敏《数据结构(c语言版)习题集》算法设计题第九章答案

严蔚敏《数据结构(c语言版)习题集》算法设计题第九章答案第九章查找int Search_Sq(SSTable ST int key)//在有序表上顺序查找的算法监视哨设在高下标端{ST elem[ST length+ ] key=key;for(i= ;ST elem[i] key>key;i++);if(i>ST length||ST elem[i] keyreturn i;}//Search_Sq分析:本算法查找成功情况下的平均查找长度为ST.length/2,不成功情况下为ST.length.9.26int Search_Bin_Recursive(SSTable ST,int key,int low,int high)//折半查找的递归算法{if(low>high) return 0; //查找不到时返回0mid=(low+high)/2;if(ST.elem[mid].key==key) return mid;else if(ST.elem[mid].key>key)return Search_Bin_Recursive(ST,key,low,mid-1);else return Search_Bin_Recursive(ST,key,mid+1,high);}}//Search_Bin_Recursive9.27int Locate_Bin(SST able ST,int key)//折半查找,返回小于或等于待查元素的最后一个结点号{int *r;r=ST.elem;if(keyelse if(key>=r[ST.length].key) return ST.length;low=1;high=ST.length;while(low<=high){mid=(low+high)/2;if(key>=r[mid].key&&keyreturn mid;else if(keyelse low=mid;} //本算法不存在查找失败的情况,不需要return 0;}//Locate_Bin9.28typedef struct {int maxkey;int firstloc;} Index;typedef struct {int *elem;int length;Index idx[MAXBLOCK]; //每块起始位置和最大元素,其中idx[0]不利用,其内容初始化为{0,0}以利于折半查找int blknum; //块的数目} IdxSqList; //索引顺序表类型int Search_IdxSeq(IdxSqList L,int key)//分块查找,用折半查找法确定记录所在块,块内采用顺序查找法{if(key>L.idx[L.blknum].maxkey) return ERROR; //超过最大元素low=1;high=L.blknum;found=0;while(low<=high&&!found) //折半查找记录所在块号mid{mid=(low+high)/2;if(key<=L.idx[mid].maxkey&&key>L.idx[mid-1].maxkey)found=1;else if(key>L.idx[mid].maxkey)low=mid+1;else high=mid-1;}i=L.idx[mid].firstloc; //块的下界j=i+blksize-1; //块的上界temp=L.elem[i-1]; //保存相邻元素L.elem[i-1]=key; //设置监视哨for(k=j;L.elem[k]!=key;k--); //顺序查找L.elem[i-1]=temp; //恢复元素if(kreturn k;}//Search_IdxSeq分析:在块内进行顺序查找时,如果需要设置监视哨,则必须先保存相邻块的相邻元素,以免数据丢失.9.29typedef struct {LNode *h; //h指向最小元素LNode *t; //t指向上次查找的结点} CSList;LNode *Search_CSList(CSList &L,int key)//在有序单循环链表存储结构上的查找算法,假定每次查找都成功{if(L.t->data==key) return L.t;else if(L.t->data>key)for(p=L.h,i=1;p->data!=key;p=p->next,i++);elsefor(p=L.t,i=L.tpos;p->data!=key;p=p->next,i++);L.t=p; //更新t指针return p;}//Search_CSList分析:由于题目中假定每次查找都是成功的,所以本算法中没有关于查找失败的处理.由微积分可得,在等概率情况下,平均查找长度约为n/3.9.30typedef struct {DLNode *pre;int data;DLNode *next;} DLNode;typedef struct {DLNode *sp;int length;} DSList; //供查找的双向循环链表类型DLNode *Search_DSList(DSList &L,int key)//在有序双向循环链表存储结构上的查找算法,假定每次查找都成功{p=L.sp;if(p->data>key){while(p->data>key) p=p->pre;L.sp=p;}{while(p->data next;L.sp=p;}return p;}//Search_DSList分析:本题的平均查找长度与上一题相同,也是n/3.9.31int last=0,flag=1;int Is_BSTree(Bitree T)//判断二叉树T是否二叉排序树,是则返回1,否则返回0{if(T->lchild&&flag) Is_BSTree(T->lchild);if(T->datalast=T->data;if(T->rchild&&flag) Is_BSTree(T->rchild);return flag;}//Is_BSTree9.32int last=0;void MaxLT_MinGT(BiTree T,int x)//找到二叉排序树T中小于x 的最大元素和大于x的最小元素{if(T->lchild) MaxLT_MinGT(T->lchild,x); //本算法仍是借助中序遍历来实现if(last data>=x) //找到了小于x的最大元素printf("a=%d\n",last);if(last<=x&&T->data>x) //找到了大于x的最小元素printf("b=%d\n",T->data);if(T->rchild) MaxLT_MinGT(T->rchild,x);}//MaxLT_MinGT9.33void Print_NLT(BiTree T,int x)//从大到小输出二叉排序树T中所有不小于x的元素{if(T->rchild) Print_NLT(T->rchild,x);if(T->dataprintf("%d\n",T->data);if(T->lchild) Print_NLT(T->lchild,x); //先右后左的中序遍历}//Print_NLT9.34void Delete_NLT(BiTree &T,int x)//删除二叉排序树T中所有不小于x元素结点,并释放空间{if(T->rchild) Delete_NLT(T->rchild,x);if(T->dataq=T;T=T->lchild;free(q); //如果树根不小于x,则删除树根,并以左子树的根作为新的树根if(T) Delete_NLT(T,x); //继续在左子树中执行算法}//Delete_NLT9.35void Print_Beeen(BiThrTree T,int a,int b)//打印输出后继线索二叉排序树T中所有大于a且小于b的元素{p=T;while(!p->ltag) p=p->lchild; //找到最小元素while(p&&p->data{if(p->data>a) printf("%d\n",p->data); //输出符合条件的元素if(p->rtag) p=p->rtag;else{p=p->rchild;while(!p->ltag) p=p->lchild;} //转到中序后继}//while}//Print_Beeen9.36void BSTree_Insert_Key(BiThrTree &T,int x)//在后继线索二叉排序树T中插入元素x{if(T->data{if(T->rtag) //T没有右子树时,作为右孩子插入{p=T->rchild;q=(BiThrNode*)malloc(sizeof(BiThrNode));q->data=x;T->rchild=q;T->rtag=0;q->rtag=1;q->rchild=p; //修改原线索}else BSTree_Insert_Key(T->rchild,x);//T有右子树时,插入右子树中}//ifelse if(T->data>x) //插入到左子树中{if(!T->lchild) //T没有左子树时,作为左孩子插入{q=(BiThrNode*)malloc(sizeof(BiThrNode));q->data=x;T->lchild=q;q->rtag=1;q->rchild=T; //修改自身的线索}else BSTree_Insert_Key(T->lchild,x);//T有左子树时,插入左子树中}//if}//BSTree_Insert_Key9.37。

《数据结构》第九章习题 参考答案

《数据结构》第九章习题 参考答案

《数据结构》第九章习题参考答案一、判断题(在正确说法的题后括号中打“√”,错误说法的题后括号中打“×”)1、快速排序是一种稳定的排序方法。

(×)2、在任何情况下,归并排序都比简单插入排序快。

(×)3、当待排序的元素很大时,为了交换元素的位置,移动元素要占用较多的时间,这是影响时间复杂度的主要因素。

(√)4、内排序要求数据一定要以顺序方式存储。

(×)5、直接选择排序算法在最好情况下的时间复杂度为O(n)。

( ×)6、快速排序总比简单排序快。

( ×)二、单项选择题1.在已知待排序文件已基本有序的前提下,效率最高的排序方法是(A)。

A.直接插入排序B.直接选择排序C.快速排序D.归并排序2.下列排序方法中,哪一个是稳定的排序方法?(B)A.直接选择排序B.折半插入排序C.希尔排序D.快速排序3、比较次数与排序的初始状态无关的排序方法是( B)。

A.直接插入排序B.起泡排序(时间复杂度O(n2))C.快速排序D.简单选择排序4、对一组数据(84,47,25,15,21)排序,数据的排列次序在排序的过程中的变化为(1)84 47 25 15 21 (2)15 47 25 84 21 (3)15 21 25 84 47 (4)15 21 25 47 84 则采用的排序是( A)。

A. 选择B. 冒泡C. 快速D. 插入5、快速排序方法在(D)情况下最不利于发挥其长处。

A. 要排序的数据量太大B. 要排序的数据中含有多个相同值C. 要排序的数据个数为奇数D. 要排序的数据已基本有序6、用某种排序方法对线性表{25,84,21,47,15,27,68,35,20}进行排序,各趟排序结束时的结果为:(基准)20,21,15,25,84,27,68,35,47(25)15,20,21,25,47,27,68,35,84(左20右47)15,20,21,25,35,27,47,68,84(左35右68)15,20,21,25,27,35,47,68,84 ;则采用的排序方法为(C)。

数据结构(C语言版)(第2版)课后习题答案

数据结构(C语言版)(第2版)课后习题答案

数据结构(C语言版)(第2版)课后习题答案数据结构(C语言版)(第2版)课后习题答案1. 简介数据结构是计算机科学领域中非常重要的一门学科,它研究的是数据的组织、存储和管理方式。

本文将针对《数据结构(C语言版)(第2版)》的课后习题提供答案,帮助读者更好地理解和应用数据结构。

2. 第一章: 绪论在第一章中,主要介绍了数据结构的基本概念、分类和基本操作。

以下是部分习题的答案:2.1 习题1习题描述:什么是数据结构?答案:数据结构是指数据对象中元素之间的关系,以及对这些关系进行操作的方法和技术的集合。

2.2 习题2习题描述:数据结构的分类有哪些?答案:数据结构可以分为线性结构和非线性结构。

线性结构包括线性表、栈、队列等;非线性结构包括树、图等。

3. 第二章: 线性表第二章介绍了线性表的定义、分类和实现。

以下是部分习题的答案:3.1 习题1习题描述:什么是线性表?答案:线性表是由n个数据元素a1, a2, ..., an组成的有限序列,其中元素之间存在着一一对应的关系。

3.2 习题2习题描述:线性表的分类有哪些?答案:线性表可以分为顺序表和链表。

顺序表是用一段地址连续的存储单元一次存储线性表的所有元素,而链表是采用链式存储结构,通过每个元素存储其后继元素的地址来实现元素之间的逻辑关系。

4. 第三章: 栈与队列第三章讲解了栈和队列的定义、特性和实现。

以下是部分习题的答案:4.1 习题1习题描述:栈和队列有什么区别?答案:栈是一种后进先出的线性表,只能在表尾进行插入和删除操作;队列是一种先进先出的线性表,只能在表的一端进行插入和删除操作。

4.2 习题2习题描述:栈的应用有哪些?答案:栈在计算机科学中有广泛的应用,如函数的调用和返回、括号匹配、表达式求值等。

5. 第四章: 串第四章讲解了串的定义、模式匹配和实现。

以下是部分习题的答案:5.1 习题1习题描述:什么是串?答案:串是由零个或多个字符组成的有限序列,串中的字符个数称为串的长度。

算法与数据结构答案第9章查找

算法与数据结构答案第9章查找

第9章 集合一、基础知识题假设对长度均为n 的有序的顺序表和无序的顺序表别离进行顺序查找,试在以下三种情形下别离讨论二者在等概率情形下平均查找长度是不是相同?(1)查找不成功,即表中没有和关键字K 相等的记录; (2)查找成功,且表中只有一个和关键字K 相等的记录;(3)查找成功,且表中有多个和关键字K 相等的记录,要求计算有多少个和关键字K 相等的记录。

【解答】(1)平均查找长度不相同。

前者在n+1个位置都可能失败,后者失败时的查找长度都是n+1。

(2)平均查找长度相同。

在n 个位置上都可能成功。

(3)平均查找长度不相同。

前者在某个位置上(1<=i<=n)查找成功时,和关键字K 相等的记录是持续的,而后者要查找完顺序表的全数记录。

在查找和排序算法中,监视哨的作用是什么?【解答】监视哨的作用是免去查找进程中每次都要检测整个表是不是查找完毕,提高了查找效率。

用分块查找法,有2000项的表分成多少块最理想?每块的理想长度是多少?假设每块长度为25 ,平均查找长度是多少?【解答】分成45块,每块的理想长度为45(最后一块长20)。

假设每块长25,那么平均查找长度为ASL=(80+1)/2+(25+1)/2=(顺序查找确信块),或ASL=19(折半查找确信块)。

用不同的输入顺序输入n 个关键字,可能构造出的二叉排序树具有多少种不同形态? 【解答】 证明假设二叉排序树中的一个结点存在两个小孩,那么它的中序后继结点没有左小孩,中序前驱结点没有右小孩。

【证明】依照中序遍历的概念,该结点的中序后继是其右子树上按中序遍历的第一个结点,即右子树上值最小的结点:叶子结点或仅有右子树的结点,没有左小孩;而其中序前驱是其左子树上按中序遍历的最后个结点,即左子树上值最大的结点:叶子结点或仅有左子树的结点,没有右小孩。

命题得证。

关于一个高度为h 的A VL 树,其最少结点数是多少?反之,关于一个有n 个结点的A VL 树, 其最大高度是多少? 最小高度是多少?【解答】设以N h 表示深度为h 的A VL 树中含有的最少结点数。

数据结构与算法分析C版答案

数据结构与算法分析C版答案

Data Structures and Algorithm 习题答案Preface ii1 Data Structures and Algorithms 12 Mathematical Preliminaries 53 Algorithm Analysis 174 Lists, Stacks, and Queues 235 Binary Trees 326 General Trees 407 Internal Sorting 468 File Processing and External Sorting 549Searching 5810 Indexing 6411 Graphs 6912 Lists and Arrays Revisited 7613 Advanced Tree Structures 82iii Contents14 Analysis Techniques 8815 Limits to Computation 94PrefaceContained herein are the solutions to all exercises from the textbook A Practical Introduction to Data Structures and Algorithm Analysis, 2nd edition.For most of the problems requiring an algorithm I have given actual code. Ina few cases I have presented pseudocode. Please be aware that the code presented in this manual has not actually been compiled and tested. While I believe the algorithmsto be essentially correct, there may be errors in syntax as well as semantics. Most importantly, these solutions provide a guide to the instructor as to the intendedanswer, rather than usable programs.1Data Structures and AlgorithmsInstructor’s note: Unlike the other chapters, many of the questions in this chapter are not really suitable for graded work. The questions are mainly intended to get students thinking about data structures issues.This question does not have a specific right answer, provided the student keeps to the spirit of the question. Students may have trouble with the concept of “operations.”This exercise asks the student to expand on their concept of an integer representation.A good answer is described by Project , where a singly-linkedlist is suggested. The most straightforward implementation stores each digitin its own list node, with digits stored in reverse order. Addition and multiplicationare implemented by what amounts to grade-school arithmetic. Foraddition, simply march down in parallel through the two lists representingthe operands, at each digit appending to a new list the appropriate partial sum and bringing forward a carry bit as necessary. For multiplication, combine the addition function with a new function that multiplies a single digitby an integer. Exponentiation can be done either by repeated multiplication (not really practical) or by the traditional Θ(log n)-time algorithm based on the binary representation of the exponent. Discovering this faster algorithm will be beyond the reach of most students, so should not be required.A sample ADT for character strings might look as follows (with the normal interpretation of the function names assumed).Chap. 1 Data Structures and AlgorithmsSomeIn C++, this is 1for s1<s2; 0 for s1=s2;int strcmp(String s1, String s2)One’s compliment stores the binary representation of positive numbers, and stores the binary representation of a negative number with the bits inverted. Two’s compliment is the same, except t hat a negative number has its bits inverted and then one is added (for reasons of efficiency in hardware implementation).This representation is the physical implementation of an ADTdefined by the normal arithmetic operations, declarations, and other support given by the programming language for integers.An ADT for two-dimensional arrays might look as follows.Matrix add(Matrix M1, Matrix M2);Matrix multiply(Matrix M1, Matrix M2);Matrix transpose(Matrix M1);void setvalue(Matrix M1, int row, int col, int val);int getvalue(Matrix M1, int row, int col);List getrow(Matrix M1, int row);One implementation for the sparse matrix is described in Section Another implementationis a hash table whose search key is a concatenation of the matrix coordinates.Every problem certainly does not have an algorithm. As discussed in Chapter 15,there are a number of reasons why this might be the case. Some problems don’t have a sufficiently clear definition. Some problems, such as the halting problem, are non-computable. For some problems, such as one typically studied by artificial intelligence researchers, we simply don’t know a solution.We must assume that by “algorithm” we mean something composed of steps areof a nature that they can be performed by a computer. If so, than any algorithm can be expressed in C++. In particular, if an algorithm can be expressed in any other computer programming language, then it can be expressed in C++, since all (sufficiently general) computer programming languages compute the same set of functions.The primitive operations are (1) adding new words to the dictionary and (2) searching the dictionary for a given word. Typically, dictionary access involves some sort of pre-processing of the word to arrive at the “root” of the word.A twenty page document (single spaced) is likely to contain about 20,000 words. A user may be willing to wait a few seconds between individual “hits” of mis-spelled words, or perhaps up to a minute for the whole document to be processed. This means that a check for an individual word can take about 10-20 ms. Users will typically insert individual words into the dictionary interactively, so this process cantake a couple of seconds. Thus, search must be much more efficient than insertion.The user should be able to find a city based on a variety of attributes (name, location,perhaps characteristics such as population size). The user should also be able to insertand delete cities. These are the fundamental operations of any database system: search, insertion and deletion.A reasonable database has a time constraint that will satisfy the patience of a typicaluser. For an insert, delete, or exact match query, a few seconds is satisfactory. If thedatabase is meant to support range queries and mass deletions, the entire operation may be allowed to take longer, perhaps on the order of a minute. However, the time spent to process individual cities within the range must be appropriately reduced. Inpractice, the data representation will need to be such that it accommodates efficient processing to meet these time constraints. In particular, it may be necessary to supportoperations that process range queries efficiently by processing all cities in the range as a batch, rather than as a series of operations on individual cities.Students at this level are likely already familiar with binary search. Thus, theyshould typically respond with sequential search and binary search. Binary search should be described as better since it typically needs to make fewer comparisons (and thus is likely to be much faster).The answer to this question is discussed in Chapter 8. Typical measures of cost will be number of comparisons and number of swaps. Tests should include running timings on sorted, reverse sorted, and random lists of various sizes.Chap. 1 Data Structures and AlgorithmsThe first part is easy with the hint, but the second part is rather difficult to do withouta stack.a) bool checkstring(string S) {int count = 0;for (int i=0; i<length(S); i++)if (S[i] == ’(’) count++;if (S[i] == ’)’) {if (count == 0) return FALSE;count--;}}if (count == 0) return TRUE;else return FALSE;}b) int checkstring(String Str) {Stack S;int count = 0;for (int i=0; i<length(S); i++)if (S[i] == ’(’)(i);if (S[i] == ’)’) {if ()) return i;();}}if ()) return -1;else return ();}Answers to this question are discussed in Section .This is somewhat different from writing sorting algorithms for a computer, since person’s “working space” is typically limited, as is their ability to physically manipulatethe pieces of paper. Nonetheless, many of the common sorting algorithms have their analogs to solutions for this problem. Most typical answers will be insertion sort, variations on mergesort, and variations on binsort.Answers to this question are discussed in Chapter 8.2Mathematical Preliminaries(a) Not reflexive if the set has any members. One could argue it is symmetric, antisymmetric, and transitive, since no element violate any ofthe rules.(b)Not reflexive (for any female). Not symmetric (consider a brother andsister). Not antisymmetric (consider two brothers). Transitive (for any3 brothers).(c)Not reflexive. Not symmetric, and is antisymmetric. Not transitive(only goes one level).(d)Not reflexive (for nearly all numbers). Symmetric since a+ b= b+ a,so not antisymmetric. Transitive, but vacuously so (there can be nodistinct a, b,and cwhere aRband bRc).(e)Reflexive. Symmetric, so not antisymmetric. Transitive (but sort of vacuous).(f)Reflexive – check all the cases. Since it is only true when x= y,itis technically symmetric and antisymmetric, but rather vacuous. Likewise,it is technically transitive, but vacuous.In general, prove that something is an equivalence relation by proving that it is reflexive, symmetric, and transitive.(a)This is an equivalence that effectively splits the integers into odd andeven sets. It is reflexive (x+ xis even for any integer x), symmetric(since x+ y= y+ x) and transitive (since you are always adding twoodd or even numbers for any satisfactory a, b,and c).(b)This is not an equivalence. To begin with, it is not reflexive for any integer.(c)This is an equivalence that divides the non-zero rational numbers into positive and negative. It is reflexive since x˙x>0. It is symmetric sincexy˙= yx˙. It is transitive since any two members of the given classsatisfy the relationship.5Chap. 2 Mathematical Preliminaries(d)This is not an equivalance relation since it is not symmetric. For example, a=1and b=2.(e)This is an eqivalance relation that divides the rationals based on their fractional values. It is reflexive since for all a,=0. It is symmetricsince if=xthen=.x. It is transitive since any two rationalswith the same fractional value will yeild an integer.(f)This is not an equivalance relation since it is not transitive. For example, 4.2=2and 2.0=2,but 4.0=4.A relation is a partial ordering if it is antisymmetric and transitive. (a)Not a partial ordering because it is not transitive.(b)Is a partial ordering bacause it is antisymmetric (if ais an ancestor ofb, then bcannot be an ancestor of a) and transitive (since the ancestorof an ancestor is an ancestor).(c)Is a partial ordering bacause it is antisymmetric (if ais older than b,then bcannot be older than a) and transitive (since if ais older than band bis older than c, ais older than c).(d)Not a partial ordering, since it is not antisymmetric for any pair of sisters.(e)Not a partial ordering because it is not antisymmetric.(f)This is a partial ordering. It is antisymmetric (no violations exist) and transitive (no violations exist).A total ordering can be viewed as a permuation of the elements. Since there are n!permuations of nelements, there must be n!total orderings.This proposed ADT is inspired by the list ADT of Chapter 4.void clear();void insert(int);void remove(int);void sizeof();bool isEmpty();bool isInSet(int);This proposed ADT is inspired by the list ADT of Chapter 4. Note that whileit is similiar to the operations proposed for Question , the behaviour is somewhat different.void clear();void insert(int);void remove(int);void sizeof();7bool isEmpty();long ifact(int n) {The iterative version requires careful examination to understand whatit does, or to have confidence that it works as claimed.(b)Fibr is so much slower than Fibi because Fibr re-computes thebulk of the series twice to get the two values to add. What is muchworse, the recursive calls to compute the subexpressions also re-computethe bulk of the series, and do so recursively. The result is an exponential explosion. In contrast, Fibicomputes each value in the seriesexactly once, and so its running time is proportional to n.void GenTOH(int n, POLE goal, POLE t1, POLE t2,POLE* curr) {if (curr[n] == goal) Put others on t1.GenTOH(n-1, t1, goal, t2, curr);move(t2, goal);GenTOH(n-1, goal, t1, t2, curr); In theory, this series approaches, but never reaches,0, so it will go on forever. In practice, the value should become computationally indistinguishable from zero, and terminate. However, this is terrible programming practice.Chap. 2 Mathematical Preliminariesvoid allpermute(int array[], int n, int currpos) {if (currpos == (n-1)} {printout(array);return;}for (int i=currpos; i<n; i++) {swap(array, currpos, i);allpermute(array, n, currpos+1);swap(array, currpos, i); The idea is the print out theelements at the indicated bit positions within the set. If we do this for values in the range 0 to 2n.1, we will get the entire powerset.void powerset(int n) {for (int i=0; i<ipow(2, n); i++) {for (int j=0; j<n; j++)if (bitposition(n, j) == 1) cout << j << " ";cout << endl;}Proof: Assume that there is a largest prime number. Call it Pn,the nthlargest prime number, and label all of the primes in order P1 =2, P2 =3,and so on. Now, consider the number Cformed by multiplying all of the nprime numbers together. The value C+1is not divisible by any of the nprime numbers. C+1is a prime number larger than Pn, a contradiction.Thus, we conclude that there is no largest prime number. .Note: This problem is harder than most sophomore level students can handle.√Proof: The proof is by contradiction. Assume that 2is rational. By definition, there exist integers pand qsuch that√p2=,qwhere pand qhave no common factors (that is, the fraction p/qis in lowestterms). By squaring both sides and doing some simple algebraic manipulation, we get2p2=2q222q= pSince p2 must be even, pmust be even. Thus,9222q=4(p)222q=2(p)2This implies that q2 is also even. Thus, pand qare both even, which contra√dicts the requirement that pand qhave no common factors. Thus, 2mustbe irrational. .The leftmost summation sums the integers from 1 to n. The second summation merely reverses this order, summing the numbers from n.1+1=ndown to n.n+1=1. The third summation has a variable substitution ofi, with a corresponding substitution in the summation bounds. Thus,it is also the summation of n.0=nto n.(n.1)=1.Proof:(a) Base case.For n=1, 12 = [2(1)3 +3(1)2 +1]/6=1. Thus, theformula is correct for the base case.(b) Induction Hypothesis.2(n.1)3 +3(n.1)2 +(n.1)i2 =.6i=1(c) Induction Step.i2 i2 +n2=i=1 i=12(n.1)3 +3(n.1)2 +(n.1)2=+n62n3 .6n2 +6n.2+3n2 .6n+3+n.1 2=+n62n3 +3n2 +n=.6Thus, the theorem is proved by mathematical induction. .Proof:(a) Base case.For n=1, 1/2=1.1/2=1/2. Thus, the formula iscorrect for the base case.(b) Induction Hypothesis.11=1..2i=1Chap. 2 Mathematical Preliminaries(c) Induction Step.1 11=+iin222i=1 i=111=1.+n221=1..n2Thus, the theorem is proved by mathematical induction. . Proof:(a) Base case. For n=0, 20 =21 .1=1. Thus, the formula is correctfor the base case.(b) Induction Hypothesis.2i=2n.1.i=0(c) Induction Step.2i=2i+2ni=0 i=0n=2n.1+2n+1 .1=2.Thus, the theorem is proved by mathematical induction. .The closed form solution is 3n+, which I deduced by noting that 3F (n).2n+1 .3F(n)=2F(n)=3. Now, to verify that this is correct, use mathematical induction as follows.For the base case, F(1)=3= .2The induction hypothesis is that =(3n.3)/2.i=1So,3i=3i+3ni=1 i=13n.3n= +32n+1 .33= .2Thus, the theorem is proved by mathematical induction.11nTheorem (2i)=n2 +n.i=1(a) Proof: We know from Example that the sum of the first noddnumbers is ith even number is simply one greater than the ithodd number. Since we are adding nsuch numbers, the sum must be n greater, or n2 +n. .(b) Proof: Base case: n=1yields 2=12 +1, which is true.Induction Hypothesis:2i=(n.1)2 +(n.1).i=1Induction Step: The sum of the first neven numbers is simply the sum of the first n.1even numbers plus the nth even number.2i=( 2i)+2ni=1 i=1=(n.1)2 +(n.1)+2n=(n2 .2n+1)+(n.1)+2n= n2 .n+2n= n2 +n.nThus, by mathematical induction, 2i=n2 +n. .i=1Proof:52Base case. For n=1,Fib(1) = 1 <n=2,Fib(2) = 1 <(5).3Thus, the formula is correct for the base case.Induction Hypothesis. For all positive integers i<n,5 iFib(i)<().3Induction Step. Fib(n)=Fib(n.1)+Fib(n.2)and, by the InductionHypothesis, Fib(n.1)<(5) and Fib(n.3355Fib(n) <() +()3355 5<() +()333Chap. 2 Mathematical Preliminaries85= ()3355<()2()33n5= .3Thus, the theorem is proved by mathematical induction. .Proof:12(1+1)23 =(a) Base case. For n=1, 1=1. Thus, the formula is correct4for the base case.(b) Induction Hypothesis.22(n.1)ni3 = .4i=0(c) Induction Step.n2(n.1)n2i33=+n4i=02n4 .2n3 +n3=+n4n4 +2n3 +n2=4n2(n2 +2n+2)=42n2(n+1)=4Thus, the theorem is proved by mathematical induction..(a) Proof: By contradiction. Assume that the theorem is false. Then, each pigeonhole contains at most 1 pigeon. Since there are nholes, there isroom for only npigeons. This contradicts the fact that a total of n+1pigeons are within the nholes. Thus, the theorem must be correct. .(b) Proof:i. Base case.For one pigeon hole and two pigeons, there must betwo pigeons in the hole.ii. Induction Hypothesis.For npigeons in n.1holes, some holemust contain at least two pigeons.13iii. Induction Step. Consider the case where n+1pigeons are in nholes. Eliminate one hole at random. If it contains one pigeon, eliminate it as well, and by the induction hypothesis some otherhole must contain at least two pigeons. If it contains no pigeons, then again by the induction hypothesis some other hole must contain at least two pigeons (with an extra pigeon yet to be placed). Ifit contains more than one pigeon, then it fits the requirements of the theorem directly..(a)When we add the nth line, we create nnew regions. But, we startwith one region even when there are no lines. Thus, the recurrence is F(n)=F(n.1)+n+1.(b) This is equivalent to the summation F(n)=1+ i=1 ni.(c) This is close to a summation we already know (equation .Base case: T(n.1)=1=1(1+1)/2.Induction hypothesis: T(n.1)=(n.1)(n)/2.Induction step:T(n)= T(n.1)+n=(n.1)(n)/2+n= n(n+1)/2.Thus, the theorem is proved by mathematical induction.If we expand the recurrence, we getT(n)=2T(n.1)+1=2(2T(n.2)+1)+1)=4T(n.2+2+1.Expanding again yieldsT(n)=8T(n.3)+4+2+1.From this, we can deduce a pattern and hypothesize that the recurrence is equivalent tonT(n)= .12i=2n.1.i=0To prove this formula is in fact the proper closed form solution, we use mathematical induction.Base case: T(1)=21 .1=1.14Chap. 2 Mathematical PreliminariesInduction hypothesis: T(n.1)= .1.Induction step:T(n)=2T(n.1)+1= 2 .1) + 1=2n.1.Thus, as proved by mathematical induction, this formula is indeed the correctclosed form solution for the recurrence.(a)The probability is for each choice.(b)The average number of “1” bits is n/2, since each position hasproba bility of being “1.”(c)The leftmost “1” will be the leftmost bit (call it position 0) with probability ; in position 1 with probability , and so on. The numberof positions we must examine is 1 in the case where the leftmost “1” isin position 0; 2 when it is in position 1, and so on. Thus, the expectedcost is the value of the summationni.2ii=1The closed form for this summation is 2 .n+2, or just less than two.2nThus, we expect to visit on average just less than two positions. (Studentsat this point will probably not be able to solve this summation,and it is not given in the book.)There are at least two ways to approach this problem. One is to estimate the volume directly. The second is to generate volume as a function of weight. This is especially easy if using the metric system, assuming that the human body is roughly the density of water. So a 50 Kilo person has a volumeslightly less than 50 liters; a 160 pound person has a volume slightly less than 20 gallons.(a) Image representations vary considerably, so the answer will vary as a result. One example answer is: Consider VGA standard size, full-color(24 bit) images, which is 3 ×640 ×480, or just less than 1 Mbyte perimage. The full database requires some 30-35 CDs.(b)Since we needed 30-35 CDs before, compressing by a factor of 10 isnot sufficient to get the database onto one CD.[Note that if the student picked a smaller format, such as estimating thesize of a “typical” gif image, the result might well fit onto a single CD.](I saw this problem in John Bentley’s Programming Pearls.) Approach 1:The model is Depth X Width X Flow where Depth and Width are in milesand Flow is in miles/day. The Mississippi river at its mouth is about 1/4 mile wide and 100 feet (1/50 mile) deep, with a flow of around 15 miles/hour =360 miles/day. Thus, the flow is about 2 cubic miles/day.Approach 2: What goes out must equal what goes in. The model is Area XRainfall where Area is in square miles and Rainfall is in (linear) miles/day. The Mississipi watershed is about 1000 X 1000 miles, and the average rainfalis about 40 inches/year ≈.1 inches/day ≈.000002 miles/day (2 X .Thus, the flow is about 2 cubic miles/day.Note that the student should NOT be providing answers that look like theywere done using a calculator. This is supposed to be an exercise in estimation! The amount of the mortgage is irrelevant, since this is a question about rates. However, to give some numbers to help you visualize the problem, pick a$100,000 mortgage. The up-front charge would be $1,000, and the savingswould be 1/4% each payment over the life of the mortgage. The monthlycharge will be on the remaining principle, being the highest at first and gradually reducing over time. But, that has little effect for the first few years.At the grossest approximation, you paid 1% to start and will save 1/4% each year, requiring 4 years. To be more precise, 8% of $100,000 is $8,000, while7 3/4% is $7,750 (for the first year), with a little less interest paid (and therefore saved) in following years. This will require a payback period of slightlyover 4 years to save $1000. If the money had been invested, then in 5 yearsthe investment would be worth about $1300 (at 5would be close to 5 1/2years.Disk drive seek time is somewhere around 10 milliseconds or a little lessin 2000. RAM memory requires around 50 nanoseconds – much less thana microsecond. Given that there are about 30 million seconds in a year, a machine capable of executing at 100 MIPS would execute about 3 billionbillion (3 .1018) instructions in a year.Typical books have around 500 pages/inch of thickness, so one million pages requires 2000 inches or 150-200 feet of bookshelf. This would be in excess of 50 typical shelves, or 10-20 bookshelves. It is within the realm of possibility that an individual home has this many books, but it is rather unusual.A typical page has around 400 words (best way to derive this is to estimatethe number of words/line and lines/page), and the book has around 500 pages,so the total is around 200,000 words.16Chap. 2 Mathematical PreliminariesAn hour has 3600 seconds, so one million seconds is a bit less than 300 hours.A good estimater will notice that 3600 is about 10% greater than 3333, so the actual number of hours is about 10% less than 300, or close to 270. (The real value is just under 278). Of course, this is just over 11 days.Well over 100,000, depending on what you wish to classify as a city or town. The real question is what technique the student uses.(a) The time required is 1 minute for the first mile, then 60/59 minutesfor the second mile, and so on until the last mile requires 60/1=60minutes. The result is the following summation.60 6060/i=60 1/i=60H60.i=1 i=1(b)This is actually quite easy. The man will never reach his destination,since his speed approaches zero as he approaches the end of the journey.3Algorithm AnalysisNote that nis a positive integer.5nlog nis most efficient for n=1.2nis most efficient when 2 ≤n≤4.10nis most efficient for all n>5. 20nand 2nare never moreefficient than the other choices.Both log3 nand log2 nwill have value 0 when n=1.Otherwise, 2 is the most efficient expression for all n>1.2/32 3n2 log3nlog2 nn20n4nn!.(a)n+6 inputs (an additive amount, independent of n).(b)8ninputs (a multiplicative factor).(c)64ninputs.100n.10n.√About (actually, 3 100n).n+6.(a)These questions are quite hard. If f(n)=2n= x, then f(2n)=22n=2(2n)2 = x.(b)The answer is 2(nlog2 3). Extending from part (a), we need some way tomake the growth rate even higher. In particular, we seek some way tolog2 3 =make the exponent go up by a factor of 3. Note that, if f(n)= n)=2log2 3log2 3 =3x y, then f(2nn. So, we combine this observationwith part (a) to get the desired answer.First, we need to find constants cand nosuch that 1 ≤c×1 for n>n0.This is true for any positive value c<1 and any positive value of n0 (since nplays no role in the equation).Next, we need to find constants cand n0 such that 1 ≤c×nfor n>n0.This is true for, say, c=1 and n0 =1.1718Chap. 3 Algorithm AnalysisOther values for n0 and care possible than what is given here.(a)The upper bound is O(n) for n0 >0 and c= c1. The lower bound isΩ(n) for n0 >0 and c= c1.(b)The upper bound is O(n3) for n0 >c3 and c= c2 +1. The lowerbound is Ω(n3) for n0 >c3 and c= c2.(c)The upper bound is O(nlog n) for n0 >c5 and c= c4 +1. The lowerbound is Ω(nlog n) for n0 >c5 and c= c4.(d)The upper bound is O(2n) for n0 >c7100 and c= c6 +lower bound is Ω(2n) for n0 >c7100 and c= c6. (100 is used forconvenience to insure that 2n>n6)(a) f(n)=Θ(g(n)) since log n2 = 2 log n.(b)f(n) is in Ω(g(n)) since ncgrows faster than log ncfor any c.(c)f(n) is in Ω(g(n)). Dividing both sides by log n, we see that log n grows faster than 1.(d)f(n) is in Ω(g(n)). If we take both f(n) and g(n) as exponents for 2,2we get 2non one side and 2log2 n=(2log n)2 = n2 on the other, and ngrows slower than 2n.(e)f(n) is in Ω(g(n)). Dividing both sides by log nand throwing awaythe low order terms, we see that ngrows faster than 1.(f)f(n)=Θ(g(n)) since log 10 and 10 are both constants.2(g)f(n) is in Ω(g(n)) since 2ngrows faster than 10n.(h)f(n) is in O(g(n)). 3n=, and if we divide both sides by 2n,we see thatgrows faster than 1.(a) This fragment is Θ(1).(b)This fragment is Θ(n) since the outer loop is executed a constant number。

算法与数据结构C语言习题参考答案6-9章

算法与数据结构C语言习题参考答案6-9章

1. 现在有一个已排序的字典,请改写二分法检索算法,使之当排序码key在字典中重复出现时算法能找出第一个key出现的元素下标(用*position来保存)。

保持算法时间代价为O(log n)。

【答】思路一般的二分法检索算法只要找出关键码key在字典中的一个下标。

在比较的过程中,一旦发现相等,记录下当前下标mid就符合要求。

程序如下:数据结构字典采用6.1.4节中的顺序表示法。

typedef int KeyType;typedef int DataType;二分法检索算法int binarySearch(SeqDictionary * pdic, KeyType key, int * position) {int low, mid, high;low = 0;high = pdic->n - 1;while (low <= high){mid = (low + high) / 2;if (pdic->element[mid].key = = key) {*position = mid;return TRUE;}elseif (pdic->element[mid].key > key)high = mid - 1;elselow = mid + 1;}*position = low;return FALSE;}改写后的算法想要找出关键码key在字典中第一次出现的下标。

在比较中,如果遇到相等(key与pdic->element[mid].key相等),则需要分情形讨论。

(1)如果当前下标mid等于0,或者key与pdic->element[mid-1].key不等,那么mid 一定是key第一次出现的下标,返回mid即可。

(2)如果情形(1)不成立,那么mid一定大于等于key第一次出现的下标,需要在low 和mid-1之间继续进行搜索,找出key第一次出现的下标。

数据结构c语言版课后习题答案完整版

数据结构c语言版课后习题答案完整版

数据结构c语⾔版课后习题答案完整版第1章绪论5.选择题:CCBDCA6.试分析下⾯各程序段的时间复杂度。

(1)O(1)(2)O(m*n)(3)O(n2)(4)O(log3n)(5)因为x++共执⾏了n-1+n-2+……+1= n(n-1)/2,所以执⾏时间为O(n2)(6)O(n)第2章线性表1.选择题babadbcabdcddac2.算法设计题(6)设计⼀个算法,通过⼀趟遍历在单链表中确定值最⼤的结点。

ElemType Max (LinkList L ){if(L->next==NULL) return NULL;pmax=L->next; //假定第⼀个结点中数据具有最⼤值p=L->next->next;while(p != NULL ){//如果下⼀个结点存在if(p->data > pmax->data) pmax=p;p=p->next;}return pmax->data;(7)设计⼀个算法,通过遍历⼀趟,将链表中所有结点的链接⽅向逆转,仍利⽤原表的存储空间。

void inverse(LinkList &L) {// 逆置带头结点的单链表 Lp=L->next; L->next=NULL;while ( p) {q=p->next; // q指向*p的后继p->next=L->next;L->next=p; // *p插⼊在头结点之后p = q;(10)已知长度为n的线性表A采⽤顺序存储结构,请写⼀时间复杂度为O(n)、空间复杂度为O(1)的算法,该算法删除线性表中所有值为item的数据元素。

[题⽬分析] 在顺序存储的线性表上删除元素,通常要涉及到⼀系列元素的移动(删第i个元素,第i+1⾄第n个元素要依次前移)。

本题要求删除线性表中所有值为item的数据元素,并未要求元素间的相对位置不变。

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

1. 现在有一个已排序的字典,请改写二分法检索算法,使之当排序码key在字典中重复出现时算法能找出第一个key出现的元素下标(用*position来保存)。

保持算法时间代价为O(log n)。

【答】思路一般的二分法检索算法只要找出关键码key在字典中的一个下标。

在比较的过程中,一旦发现相等,记录下当前下标mid就符合要求。

程序如下:数据结构字典采用6.1.4节中的顺序表示法。

typedef int KeyType;typedef int DataType;二分法检索算法int binarySearch(SeqDictionary * pdic, KeyType key, int * position) {int low, mid, high;low = 0;high = pdic->n - 1;while (low <= high){mid = (low + high) / 2;if (pdic->element[mid].key = = key) {*position = mid;return TRUE;}elseif (pdic->element[mid].key > key)high = mid - 1;elselow = mid + 1;}*position = low;return FALSE;}改写后的算法想要找出关键码key在字典中第一次出现的下标。

在比较中,如果遇到相等(key与pdic->element[mid].key相等),则需要分情形讨论。

(1)如果当前下标mid等于0,或者key与pdic->element[mid-1].key不等,那么mid 一定是key第一次出现的下标,返回mid即可。

(2)如果情形(1)不成立,那么mid一定大于等于key第一次出现的下标,需要在low 和mid-1之间继续进行搜索,找出key第一次出现的下标。

下面算法中,加粗的部分是对原算法的修改。

修改后的二分法检索算法int binarySearch1(SeqDictionary * pdic, KeyType key, int * position) {/*算法结束后,*position存放key第一次出现的下标*/int low, mid, high;low = 0;high = pdic->n - 1;while (low <= high){mid = (low + high) / 2;if (pdic->element[mid].key = = key) {if (mid = = 0 || key != pdic->element[mid - 1].key) {*position = mid;return TRUE;} /*此时mid就是key在字典中第一次出现的下标*/elsehigh = mid - 1; /*在左半段继续搜索*/}elseif (pdic->element[mid].key > key)high = mid - 1;elselow = mid + 1;}*position = low;return FALSE;}代价分析该算法的时间复杂度为O(log n)。

2. 试编写一算法求出指定结点在给定的二叉排序树中所在的层数。

【答】数据结构采用7.1.3节中字典的二叉排序树表示。

算法int search_layer(PBinTree pbtree, PBinTreeNode pnode) {/*返回二叉排序树*pbtree中结点*pnode所在层数,要求所给结点在树中*/ int layer = 0;PBinTreeNode p = *pbtree;while (p != NULL) {if (p->key = = pnode->key)return layer; /*查找结点成功,返回层数*/ if (p->key > pnode->key) {p = p->llink; /*进入左子树继续查找*/layer++;}else {p = p->rlink; /*进入右子树继续查找*/layer++;}}return -1; /*查找结点失败*/}代价分析假设二叉排序树有n个结点,高度是h(log n<=h<=n),算法执行的时间代价最坏为O(h)。

2注意根结点为零层。

3. 试编写一算法在给定的二叉排序树上找出任意两个不同结点最近的公共祖先(若在两结点A,B中,A是B的祖先,则认为A,B最近的公共祖先就是A)。

数据结构同上题算法int FindLowestCommonAncestor(pBinSearchNode root, int value1, int value2) {pBinSearchNode curnode = root;while(1) {if (curnode->key>value1&&curnode->key>value2)curnode = curnode->llink;else if(curnode->key<value1&&curnode->key<value2)curnode = curnode->rlink;else return curnode->key;}}4. 设计一个有效的算法,在1000个无序的元素中,挑选出其中前5个最大的元素。

【答】数据结构typedef int KeyType;typedef int DataType;typedef struct{ KeyType key; /* 排序码字段*/DataType info; /* 记录的其它字段*/}RecordNode;typedef struct{ int n; /* n为文件中的记录个数*/RecordNode *record;}SortObject;思路这里不需要整体排序,故选择一种能较快得出最终排序段的前一部分的算法改造即可,如直接选择排序,起泡排序,堆排序都能最先得出前5个最大元素。

综合考虑算法的时间代价,选择直接选择排序算法改造即可。

算法函数返回一个数组,数组中存着挑出的元素,为动态分配的。

RecordNode* Outmax(SortObject *pvector, int out){int i, j, k;RecordNode *outpart;RecordNode temp;if(out>pvector->n){printf("the given value is wrong!");return NULL;}outpart=(RecordNode*)malloc(out*sizeof(RecordNode));if(outpart==NULL){printf("No space!\n");return NULL;}for(i=0;i<out;i++){k=i;for( j=i+1;j<pvector->n;j++)if(pvector->record[j].key>pvector->record[k].key) k=j;if(k!=i){temp=pvector->record[i];pvector->record[i]=pvector->record[k];pvector->record[k]=temp;}outpart[i]=pvector->record[i];}return outpart;}代价分析O(n*m) (设从n个元素中选出m个最大元素)。

5. 写一个算法来判断对给定有向图中的指定顶点是否至少存在一条有向边指向它。

【答】图有三种表示方法:出边表(邻接表的一种),入边表(邻接表的一种)和邻接矩阵。

相应的有三种算法。

设n为顶点数,m为边数。

对于出边表,顺次搜索一遍边即可,时间代价为O(m)。

对于入边表,判断指定顶点的边表头指针是否非空即可,时间代价为O(1)。

对于邻接矩阵,搜索矩阵中指定顶点对应的列,判断其中是否有非0元即可,时间代价为O(n)。

以出边表为例,给出一个算法如下。

数据结构采用9.1.3节中有向图的邻接表(出边表)表示法。

算法int is_end(GraphList g, int k) {/*判断图g中是否有边指向第k个结点(0<=k<=g.n-1)*/EdgeList p;int i;for ( i = 0;i < g.n;i++) {p = g.vexs[i].edgelist;while (p != NULL) {if (p->endvex = = i) return 1;p = p->nextedge;}}return 0;}代价分析该算法的时间复杂度为O(m)。

6.设计一个算法,确定(无权)图中每一对结点之间的可达关系。

【答】数据结构采用图的邻接矩阵表示法。

#define MAXVEX 100typedef char * VexType;typedef int AdjType;typedef struct{VexType vexs[MAXVEX]; /*顶点信息*/AdjType arcs[MAXVEX][MAXVEX]; /*边信息*/int n; /*图的顶点个数*/}GraphMatrix;思路这里介绍Warshall算法,该算法解决了(无权)图的可达性问题。

算法用到了一个矩阵a(a作为算法的参数之一)。

开始时,对矩阵a中元素赋值,使a 与图的邻接矩阵相等。

这样,矩阵a记录的就是所有直接的边连接。

算法的核心部分是一个三重循环。

其中外重循环的循环次数为n,每次循环更新a中的元素。

循环一次后,a中记录的就是所有直接连接或者只经由结点0而形成的通路的情况。

循环k(1≤k≤n)次后,a 中记录的就是所有至多只经由结点0, 1, …, k 1而形成的通路的情况。

这样,算法结束时,矩阵a中记录的就是每一对结点之间的可达性信息。

a[i][j]为1,表示从结点i到结点j是可达的;为0,则表示不可达。

算法void warshall(GraphMatrix * pgraph, int a[][MAXVEX]) {int i, j, m;for (i = 0; i < pgraph->n; i++) /*对矩阵a中元素赋值,使a与图的邻接矩阵相等*/for ( j = 0; j < pgraph->n; j++)a[i][j] = pgraph->arcs[i][j];for ( m = 0; m < pgraph->n; m++) /*算法的核心部分,一个三重循环*/for ( i = 0; i < pgraph->n; i++)for (j = 0; j < pgraph->n; j++)a[i][j] = a[i][j] || (a[i][m] && a[m][j]);}代价分析算法的核心部分是一个三重循环,每重的循环次数为n,因此该算法的时间代价为O(n3)。

相关文档
最新文档