数据结构与算法分析 第13章 答案 Larry Nyhoff 清华大学出版社

合集下载

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

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

第八章选择题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}应用题11.(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 17012.采用快速排序时,第一趟排序过程中的数据移动如图:算法设计题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次,如果最后两个元素做一个批处理,那么比较次数和移动次数将大大减小。

《算法导论》习题答案12、13、14章

《算法导论》习题答案12、13、14章

第9章 中位数和顺序统计学
9.3-2
大于x的数至少有3n/10-6, n≥140时,易证3n/10-6 ≥n/4 小于x的数同理。
9.3-4
通过比较得到第i小元素,每次保留比较信息。 在比较过程中比这个元素小的元素构成的集合即为i – 1个 小数集合,而比较过程中比这个元素大的元素则构成了n – i 个大元素集合。不需要增加比较次数。
Preprocessing(A,k) for i←0 to k do C[i]←0 for j←1 to length[A] do C[A[j]] ←C[A[j]]+1 for i←1 to k do C[i] ←C[i]+C[i-1] Query(C,k,a,b) if b<a or b<1 or a>k return 0 if a<1 then a=1 if b>k then b=k if a≠1 then return C[b]-C[a-1] else return C[b]
0 +1
k +1
k +1
( k +1) +1
第6章 堆排序
6.4-3 不论递增还是递减,时间均为O(nlgn) 6.4-4 最坏情况下,n-1次调用MAX-HEAPIFY,运 行时间为O(nlgn)
第6章 堆排序
6.5-3
HEAP-MINIMUM(A) if heap-size[A]<1 then error”heap underflow” else return A[1] HEAP-EXTRACT-MIN(A) if heap-size[A]<1 then error”heap underflow” min<-A[1] A[1]<-A[heap-size[A]] heap-size[A]<-heap-size[A]-1 MIN-HEAPIFY(A,1) return min HEAP-DECREASE-KEY(A,i,key) if key>A[i] then error A[i]<-key while i>1 and A[PARENT(i)>A[i] do exchange A[i]<->A[PARENT(i)] i<-PARENT(i) MIN-HEAP-INSERT(A,key) heap-size[A]<-heap-size[A]+1 A[heap-size[A]]<-+∞ HEAP-DECREASE-KEY(A,heap-size[A],key)

数据结构与算法分析课后题答案

数据结构与算法分析课后题答案

Chapter 5:Hashing5.1(a)On the assumption that we add collisions to the end of the list (which is the easier way if a hash table is being built by hand),the separate chaining hash table that results is shown here.4371132361734344419996791989123456789(b)96794371198913236173434441990123456789-25-w w w .k h d a w .com课后答案网(c)96794371132361734344198941990123456789(d)1989cannot be inserted into the table because hash 2(1989)=6,and the alternative locations 5,1,7,and 3are already taken.The table at this point is as follows:4371132361739679434441991234567895.2When rehashing,we choose a table size that is roughly twice as large and prime.In our case,the appropriate new table size is 19,with hash function h (x ) = x (mod 19).(a)Scanning down the separate chaining hash table,the new locations are 4371in list 1,1323in list 12,6173in list 17,4344in list 12,4199in list 0,9679in list 8,and 1989in list 13.(b)The new locations are 9679in bucket 8,4371in bucket 1,1989in bucket 13,1323in bucket 12,6173in bucket 17,4344in bucket 14because both 12and 13are already occu-pied,and 4199in bucket 0.-26-w ww .k h d a w.com课后答案网(c)The new locations are 9679in bucket 8,4371in bucket 1,1989in bucket 13,1323in bucket 12,6173in bucket 17,4344in bucket 16because both 12and 13are already occu-pied,and 4199in bucket 0.(d)The new locations are 9679in bucket 8,4371in bucket 1,1989in bucket 13,1323in bucket 12,6173in bucket 17,4344in bucket 15because 12is already occupied,and 4199in bucket 0.5.4We must be careful not to rehash too often.Let p be the threshold (fraction of table size)atwhich we rehash to a smaller table.Then if the new table has size N ,it contains 2pN ele-ments.This table will require rehashing after either 2N − 2pN insertions or pN deletions.Balancing these costs suggests that a good choice is p = 2/ 3.For instance,suppose we have a table of size 300.If we rehash at 200elements,then the new table size is N = 150,and we can do either 100insertions or 100deletions until a new rehash is required.If we know that insertions are more frequent than deletions,then we might choose p to be somewhat larger.If p is too close to 1.0,however,then a sequence of a small number of deletions followed by insertions can cause frequent rehashing.In the worst case,if p = 1.0,then alternating deletions and insertions both require rehashing.5.5(a)Since each table slot is eventually probed,if the table is not empty,the collision can beresolved.(b)This seems to eliminate primary clustering but not secondary clustering because all ele-ments that hash to some location willtry the same collision resolution sequence.(c,d)The running time is probably similar to quadratic probing.The advantage here is thatthe insertion can’t fail unless the table is full.(e)A method of generating numbers that are not random (or even pseudorandom)is given in the references.An alternative is to use the method in Exercise 2.7.5.6Separate chaining hashing requires the use of pointers,which costs some memory,and thestandard method of implementing calls on memory allocation routines,which typically are expensive.Linear probing is easily implemented,but performance degrades severely as the load factor increases because of primary clustering.Quadratic probing is only slightly more difficult to implement and gives good performance in practice.An insertion can fail if the table is half empty,but this is not likely.Even if it were,such an insertion would be so expensive that it wouldn’t matter and would almost certainly point up a weakness in the hash function.Double hashing eliminates primary and secondary clustering,but the compu-tation of a second hash function can be costly.Gonnet and Baeza-Yates [8]compare several hashing strategies;their results suggest that quadratic probing is the fastest method.5.7Sorting the MN records and eliminating duplicates would require O (MN log MN )timeusing a standard sorting algorithm.If terms are merged by using a hash function,then the merging time is constant per term for a total of O (MN ).If the output polynomial is small and has only O (M + N )terms,then it is easy to sort it in O ((M + N )log (M + N ))time,which is less than O (MN ).Thus the total is O (MN ).This bound is better because the model is less restrictive:Hashing is performing operations on the keys rather than just com-parison between the keys.A similar bound can be obtained by using bucket sort instead of a standard sorting algorithm.Operations such as hashing are much more expensive than comparisons in practice,so this bound might not be an improvement.On the other hand,if the output polynomial is expected to have only O (M + N )terms,then using a hash table saves a huge amount of space,since under these conditions,the hash table needs only-27-w w w .k h d a w .c o m课后答案网O (M + N )space.Another method of implementing these operations is to use a search tree instead of a hash table;a balanced tree is required because elements are inserted in the tree with too much order.A splay tree might be particularly well suited for this type of a problem because it does well with sequential paring the different ways of solving the problem is a good programming assignment.5.8The table size would be roughly 60,000entries.Each entry holds 8bytes,for a total of 480,000bytes.5.9(a)This statement is true.(b)If a word hashes to a location with value 1,there is no guarantee that the word is in the dictionary.It is possible that it just hashes to the same value as some other word in the dic-tionary.In our case,the table is approximately 10%full (30,000words in a table of 300,007),so there is a 10%chance that a word that is not in the dictionary happens to hash out to a location with value 1.(c)300,007bits is 37,501bytes on most machines.(d)As discussed in part (b),the algorithm will fail to detect one in ten misspellings on aver-age.(e)A 20-page document would have about 60misspellings.This algorithm would be expected to detect 54.A table three times as large would still fit in about 100K bytes and reduce the expected number of errors to two.This is good enough for many applications,especially since spelling detection is a very inexact science.Many misspelled words (espe-cially short ones)are still words.For instance,typing them instead of then is a misspelling that won’t be detected by any algorithm.5.10To each hash table slot,we can add an extra field that we’ll call WhereOnStack, and we cankeep an extra stack.When an insertion is first performed into a slot,we push the address (or number)of the slot onto the stack and set the WhereOnStack field to point to the top of the stack.When we access a hash table slot,we check that WhereOnStack points to a valid part of the stack and that the entry in the (middle of the)stack that is pointed to by the WhereOn-Stack field has that hash table slot as an address.5.14(2)000000100000101100101011(2)01010001011000010110111101111111(3)100101101001101110011110(3)1011110110111110(2)110011111101101111110000000001010011100101110111-28-w w w .k hd a w.c o m 课后答案网。

清华大学出版社数据结构(C++版)(第2版)课后习题答案最全整理

清华大学出版社数据结构(C++版)(第2版)课后习题答案最全整理

清华大学出版社数据结构(C++版)(第2版)课后习题答案最全整理第1 章绪论课后习题讲解1. 填空⑴()是数据的基本单位,在计算机程序中通常作为一个整体进行考虑和处理。

【解答】数据元素⑵()是数据的最小单位,()是讨论数据结构时涉及的最小数据单位。

【解答】数据项,数据元素【分析】数据结构指的是数据元素以及数据元素之间的关系。

⑶从逻辑关系上讲,数据结构主要分为()、()、()和()。

【解答】集合,线性结构,树结构,图结构⑷数据的存储结构主要有()和()两种基本方法,不论哪种存储结构,都要存储两方面的内容:()和()。

【解答】顺序存储结构,链接存储结构,数据元素,数据元素之间的关系⑸算法具有五个特性,分别是()、()、()、()、()。

【解答】有零个或多个输入,有一个或多个输出,有穷性,确定性,可行性⑹算法的描述方法通常有()、()、()和()四种,其中,()被称为算法语言。

【解答】自然语言,程序设计语言,流程图,伪代码,伪代码⑺在一般情况下,一个算法的时间复杂度是()的函数。

【解答】问题规模⑻设待处理问题的规模为n,若一个算法的时间复杂度为一个常数,则表示成数量级的形式为(),若为n*log25n,则表示成数量级的形式为()。

【解答】Ο(1),Ο(nlog2n)【分析】用大O记号表示算法的时间复杂度,需要将低次幂去掉,将最高次幂的系数去掉。

2. 选择题⑴顺序存储结构中数据元素之间的逻辑关系是由()表示的,链接存储结构中的数据元素之间的逻辑关系是由()表示的。

A 线性结构B 非线性结构C 存储位置D 指针【解答】C,D【分析】顺序存储结构就是用一维数组存储数据结构中的数据元素,其逻辑关系由存储位置(即元素在数组中的下标)表示;链接存储结构中一个数据元素对应链表中的一个结点,元素之间的逻辑关系由结点中的指针表示。

⑵假设有如下遗产继承规则:丈夫和妻子可以相互继承遗产;子女可以继承父亲或母亲的遗产;子女间不能相互继承。

数据结构第13章作业答案

数据结构第13章作业答案

数据结构第13章作业答案数据结构第1~3章作业参考答案【1.4】【解法一】⑴ 抽象数据类型复数: ADT Comple_{数据对象:D={ci|ci?R, i=1,2, 其中R为实数集}数据关系:R={| ci?D, i=1,2, 其中c1为复数实部, c2为复数虚部} 基本操作: InitComple_ (_C,v1,v2)操作结果:构造一个复数C,元素c1, c2分别被赋以参数v1, v2的值。

DestroyComple_(_C)初始条件:复数C已存在。

操作结果:销毁复数C。

GetReal(C, _e)初始条件:复数C已存在。

操作结果:用e返回复数C实部的值。

GetImaginary(C, _e)初始条件:复数C已存在。

操作结果:用e返回复数C虚部的值。

SetReal(_C, e)初始条件:复数C已存在。

操作结果:用e更新复数C实部的值。

SetImaginary(_C, e)初始条件:复数C已存在。

操作结果:用e更新复数C虚部的值。

AdditionComple_ (_C, C1, C2) 初始条件:复数C1,C2已存在。

操作结果:复数C1与复数C2相加,用复数C返回其和。

SubstractComple_(_C, C1, C2) 初始条件:复数C1,C2已存在。

操作结果:复数C1减去复数C2,用复数C返回其差。

MultipleComple_(_C, C1, C2 )初始条件:复数C1,C2已存在。

操作结果:复数C1与复数C2相乘,用复数C返回其积。

DividedComple_(_C, C1, C2)初始条件:复数C1,C2已存在,且C2≠0。

操作结果:复数C1除以复数C2,用复数C返回其商。

ModulusComple_(C, _e) 初始条件:复数C已存在。

操作结果:求复数C的模,用e返回。

ConjugateComple_(_C, C1) 初始条件:复数C1已存在。

操作结果:求复数C1的共轭复数,用复数C返回。

数据结构与算法分析 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 54 9Searching 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.1.1This 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.”1.2This exercise asks the student to expand on their concept of an integer representation.A good answer is described by Project 4.5, 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.1.3A sample ADT for character strings might look as follows (with the normal interpretation of the function names assumed).Chap. 1 Data Structures and Algorithms// Concatenate two stringsString strcat(String s1, String s2);// Return the length of a stringint length(String s1);// Extract a substring, starting at ‘start’,// and of length ‘length’String extract(String s1, int start, int length);// Get the first characterchar first(String s1);// Compare two strings: the normal C++ strcmp function.Some// convention should be indicated for how to interpretthe// return value. In C++, this is 1for s1<s2; 0 for s1=s2;// and 1 for s1>s2.int strcmp(String s1, String s2)// Copy a stringint strcpy(String source, String destination)1.4The answer to this question is provided by the ADT for lists given in Chapter 4.1.5One’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 that 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 ADT。

数据结构与算法课后习题解答

数据结构与算法课后习题解答

数据结构与算法课后习题解答数据结构与算法课后习题解答第一章绪论(参考答案)1.3 (1) O(n)(2) (2) O(n)(3) (3) O(n)(4) (4) O(n1/2)(5) (5) 执行程序段的过程中,x,y值变化如下:循环次数x y0(初始)91 1001 92 1002 93 100。

9 100 10010 101 10011 9112。

20 9921 91 98。

30 101 9831 91 97到y=0时,要执行10*100次,可记为O(10*y)=O(n)数据结构与算法课后习题解答1.5 2100 , (2/3)n , log2n , n1/2 , n3/2 , (3/2)n , nlog2n , 2 n , n! , n n第二章线性表(参考答案)在以下习题解答中,假定使用如下类型定义:(1)顺序存储结构:#define ***** 1024typedef int ElemType;// 实际上,ElemTypetypedef struct{ ElemType data[*****];int last; // last}sequenlist;(2*next;}linklist;(3)链式存储结构(双链表)typedef struct node{ElemType data;struct node *prior,*next;数据结构与算法课后习题解答}dlinklist;(4)静态链表typedef struct{ElemType data;int next;}node;node sa[*****];2.1 la,往往简称为“链表la”。

是副产品)2.2 23voidelenum个元素,且递增有序,本算法将x插入到向量A中,并保持向量的{ int i=0,j;while (ielenum A[i]=x) i++; // 查找插入位置for (j= elenum-1;jj--) A[j+1]=A[j];// 向后移动元素A[i]=x; // 插入元素数据结构与算法课后习题解答} // 算法结束24void rightrotate(ElemType A[],int n,k)// 以向量作存储结构,本算法将向量中的n个元素循环右移k位,且只用一个辅助空间。

数据结构与算法分析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 54 9Searching 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 p ractical) 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 rep resentation of positive numbers, and stores the binary representation of a negative number with the bits inverted. Two’s compliment is the same, except that 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 intelligen ce 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, they should 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 and sister). 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 class satisfy 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 while it 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=n.(n.1)=1.Proof:(a) Base case.For n=1, 12 = [2(1)3 +3(1)2 +1]/6=1. Thus, the formula 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.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= .The 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.2)<(5)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(n1)ni3 = .4i=0(c) Induction Step. n2(n.1)n2i33=+n4i=02n4 .2n3 +n3=+n4n4 +2n3 +n2=4n2(n2 +2n+2)=2n2(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=(n1)(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 correct closed 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 hasprobability 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. (Students at 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) i mages, 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 the size 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 estimate the 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)=22n2(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 =3xy, 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)。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
if (numCompares > 0) {
int last = 1; for (int i = 1; i <= numCompares; i++)
if (x[i] > x[i + 1]) {
int temp = x[i]; x[i] = x[i + 1]; x[i + 1] = temp; last = i; } recBubbleSortAux(x, last - 1); } }
Sort a list into ascending order using double-ended selection sort.
Precondition: array x contains n elements. Postcondition: The n elements of array have been sorted into
– 228 –
Chapter 13
6.
// Recursive helper function for recSelectionSort() so // it has same signature as other sorting functions.
template <typename ElementType> void recSelectionSortAux(ElementType x[], int n, int first) {
(b) Algorithm for two way bubble sort: O(n2).
(b) The functions below implement Min-Max Sort.
template <typename ElementType> void swap(ElementType x[], int a, int b) {
int temp = x[a]; x[a] = x[b]; x[b] = temp; }
// Swap smallest with first element x[minPos] = x[i]; x[i] = minValue;
// Find largest in last half of list int maxPos = n + 1 - i; int maxValue = x[maxPos];
for (int j = n/2 + 1; j <= n + 1 - i; j++) if (x[j] > maxValue) { maxPos = j; maxValue = x[j]; }
// Swap largest with last element x[maxPos] = x[n + 1 - i]; x[n + 1 - i] = maxValue;
if (x[j] < minValue) {
minValue = x[j]; minPos = j; }
if (x[j] > maxValue) {
maxValue = x[j]; maxPos = j; } }
// make sure that positioning min value doesn't overwrite max if (i == maxPos)
(b) 3, since no interchanges occur on the third pass.
(c) Worst case is when elements are in reverse order.
3. (a) After x [4] is positioned: 20 30 40 60 10 50 After x [5] is positioned: 10 20 30 40 60 50
i. if (ptr->data > ptr->next->data) (1) swap(ptr->data, ptr->next-&gptr = ptr->next c. lastSwap = lastPtr
9. (a) Elements of x after each pass: left to right: 30 80 20 60 70 10 90 50 40 100 right to left: 10 30 80 20 60 70 40 90 50 100 left to right: 10 30 20 60 70 40 80 50 90 100 right to left: 10 20 30 40 60 70 50 80 90 100 left to right: 10 20 30 40 60 50 70 80 90 100 right to left: 10 20 30 40 50 60 70 80 90 100 left to right: 10 20 30 40 50 60 70 80 90 100 right to left: 10 20 30 40 50 60 70 80 90 100
x[minPos] = x[first]; x[first] = minValue;
recSelectionSortAux(x, n, first + 1); } }
/* recursive SelectionSort */ template <typename ElementType> void recSelectionSort(ElementType x[], int size) { recSelectionSortAux(x, size, 0); }
minValue = maxValue = x[i]; minPos = maxPos = i;
// find min and max values among x[i], . . ., x[n]
– 226 –
Chapter 13
for (int j = i+1; j <= n-i+1; j++) {
// Find smallest in first half of list for (int i = 1; i <= n/2; i++) {
int minPos = i; int minValue = x[i];
for (int j = i + 1; j <= n/2; j++) if (x[j] < minValue) { minPos = j; minValue = x[j]; }
1. If first->next == 0 // empty list terminate this algorithm.
Else continue with the following: 2. Initialize lastPtr = 0, lastSwap = first. 3. While (lastSwap->next != 0)
ascending order. --------------------------------------------------------------------*/ {
int minValue, maxValue, minPos, maxPos;
for (int i = 1; i <= n/2; i++) {
(b) If the list is in increasing order; no interchanges are required.
4. (a) After one pass: After two passes:
10 50 60 30 40 70 10 30 40 50 60 70
(b) Function to perform double-ended selection sort:
– 227 –
Chapter 13
template <typename ElementType> void minMaxSort(ElementType x[], int n) {
// Create rainbow pattern for (int i = 1; i <= n/2; i++)
if (x[i] > x[n + 1 - i]) swap(x, i, n + 1 - i);
Chapter 13
Chapter 13: Sorting
Exercises 13.1
1. After first pass, elements of x are: 10 50 70 30 40 60.
After second pass:
10 30 70 50 40 60.
2. (a) 60 70 50 40 20 10 70 60 50 40 20 10
There are 5 passes for step 2. x[i]'s are:
After first pass: After second pass: After third pass: After fourth pass: After fifth pass:
10 50 40 20 60 70 30 90 80 100 10 20 40 30 60 70 50 80 90 100 10 20 30 40 60 70 50 80 90 100 10 20 30 40 50 60 70 80 90 100 10 20 30 40 50 60 70 80 90 100
maxPos = minPos;
x[minPos] = x[i]; x[i] = minValue; x[maxPos] = x[n-i+1]; x[n-i+1] = maxValue; } }
(c) Computing time is O(n2).
相关文档
最新文档