算法导论 第三版 第七章 答案 英
南开大学算法导论第七章课件
Ford-Fulkerson终止时的流有什么性质?
39
最大流与最小割
定理7.9 如果f是使得剩余图Gf中没有s-t 路径的一个s-t流,那么在G中存在一个 s-t割(A*,B*)使得v(f)=(A*,B*).因此,f有 G中任何流的最大值,且(A*,B*)有G中任 何s-t割的最小容量。 最大流最小割定理. [Ford-Fulkerson 1956] 最大流的值等于最小割
5
最大流问题
1. 2.
流的定义: s-t流是一个函数f,它把每条边e映射到 + E → R 一个非负实数f: ,值f(e)表示由边 e携带的流量,一个流f必须满足下面两 个性质: (容量条件)0<=f(e)<=Ce (守恒条件)除了s,t外,对每个结点v,满 足 ∑ f ( e ) = ∑ f ( e)
3
7.1 最大流问题
9 9 9
用图对交通网络建模 比如公路系统:边是公路,结点交叉路口 比如计算机网络:边是链接线,结点是开关 比如管网:边是输送些体的管道,结点是管道 连接点 抽象出来的要素: 边上的容量; 源点;终点;交通量通过边运送
4
最大流问题
流网络 有向图G=(V,E) 每条边关联一个容量,非负数Ce. 存在单一源点s, 以及单一汇点t
42
最大流与最小割
设流f没有增广路径. 定义集合A 是剩余图Gf中从源点s可达顶点集合. 根据定义,那么s ∈ A;终点 t ∉ A, ∈ B. 如果e=(u,v), u∈A,v∈B,那么f(e)=c(e); 如果e’=(u’,v’), u’∈B,v’∈A,那么f(e’)=0.
v( f ) = =
24
算法导论思考题7_2对区间的模糊排序
算法导论思考题7_2对区间的模糊排序这个学期在做算法设计课的助教,很多题以前做过就忘记了,重做特地记录下。
《算法导论》chapter7 problem7-6对区间的模糊排序考虑这样⼀种排序问题,即⽆法准确的知道等排序的各个数字到底是多⼤.对于其中的每个数字,我们只知道它落在实轴上的某个区间内.亦即,给定的 n 个形如[ai, bi ]的闭区间,其中ai,≤bi .算法的⽬标是对这些区间进⾏模糊排序(fuzzy-sort),亦即,产⽣各区间的⼀个排序<i1, i2, i3, i4,…in >,使得存在⼀个 cj ∈[ai, bi ],满⾜c1≤c2≤…≤cn .a)为n个区间的模糊排序设计⼀个算法,你的算法应该具有算法的⼀般结构,它可以快速排序左部端点(即各ai ),也要能充分利⽤重叠区间来改善运⾏时间.(随着各区间重叠得越来越多,对各区间的排序的问题会变得越来越容易,你的算法应该能充分利⽤这种重叠.)b)证明: 在⼀般情况下,你的算法的区望运⾏时间为 O(n*lgn),但当所有的区间都重叠时,期望的运⾏时间为O(n) (亦即,当存在⼀个值 x, 使得对所有的 i, 都有x∈[ai, bi ] ).你的算法不应显式的检查这种情况,⽽是应当随着重叠量的增加,性能⾃然地有所改善.解答a. 算法思想基本是仿快速排序对区间进⾏排序。
难点在于如何充分利⽤重叠区间来改善运⾏时间?其关键在于Partion()的设计。
对于如何充分利⽤重叠区间,解决思路是在调⽤Partion()划分时,区间如果重叠的部分,就把它们看做是相等的,并提取公共部分继续划分。
即对于区间[ai,bi],[aj,bj],它们⼤⼩分为三种情况。
if(bi<aj)那么[ai,bi]<[aj,bj]else if(bj<ai)那么[aj,bj]<[ai,bi]else [ai,bi]=[aj,bj]。
⽹上其它⼈的解答,思路都是类似的,不过看了⼏个版本,不少⼈在代码实现上多少有点bug。
【课后习题及答案】《计算机算法设计与分析(第三版)课后习题答案详解
精品课程 课后习题答案第 1 章 算 法 概 述习蹬 1- 1函数的渐近表达式求下列函数的渐近表达式:3, f + 10 n ; 1l 匀10·+·2'' ; 分析与解答: 3矿+10n 二. ( ) ( 4 ) ;,l / 10+ 2 擒 = 0 ( 2” ) ; 2.1-t- l 过 一( ){ 1 ) ;lo 耟. ; t = ( ) ( l (1g1.1) ; I O l og 守 =('i ?!), 21 + 1;, 1; l o g n ' ; 10lv g3飞习题 1- 21() . l )和() ( 2 )的区别试论 ( )( l ) 和 () ( 2 )的区别. 分析与觞答:根据符号()的定义易知0 (1 ) = 0( 2)。
用()(1) 或 0 ( 2 ) 表示同一个函数时 ,差别仅在于 其中的祜数因子。
习题 1- 4 按渐近阶排列表达式按照渐近阶从低到高的顺序排列以下表达式,4n \排在哪一位?分析与解答:l ()g n , 3入 20:ri, 2 . n 2/又 义叫 应该3飞 n!。
, 函 数 排列 顺 序 如 下 : 2 .l og t , n23 、20n, 4,i-, 按 浙 近 阶从 低到尚 习题 1- 5箕法效宇( l ) 假设某符法在椋人栽模为”时的计算时间为 T (,t) = 3 X 2又 在某 台计算机上实现井 完成该算 法的时间为1 秒.现有另一台计算机,其运行速度为第一台的 64 倍,那么在这台新 机器 十用 同 一 符 法在 t 秒 内 能 招 轮人规模为多大的间题?( 2) 若上述芬法的计算时间改进为 T ( n )=r/'能解轴入规枑为多大的问烦?( 3) 若 上述算法的计算时间进一步改进为 T (11) = 8 ,f 秒和可能解输人规筷 为多 大的问 题?分析与解答 :其余 条 件不 变 ,则 在新 机 器上用i 秒时间其 余 条 件 不 变 ,那么在新机器上用"赁法 在 t · 秒1引能 解输人规模 为 n l 的问题。
范里安高微第三版1-7章奇数习题答案
( p, w) p
1 1 a
w
a a 1
(a
a 1 a
a
1 1 a
) p
1 1 a
w
a a 1
(a) ,
其中 (a ) 是严格正的, 0 a 1 。 海赛阵现在可以写成
2 ( p, w) 2 p 2 D ( p, w) 2 ( p, w) wp
微分,我们得
d ln(w2 x 2 w1 x1 ) d ln( x 2 x1 ) 1 1 。 d ln(w2 w1 )) d ln TRS
2.7.a 我们想要最大化
20 x x 2 wx 。一阶条件是 20 2 x w 0 。
2.7.b 由于最优的 x 为零,利润关于 x 的导数在 x 0 点必为非正的:当 x 0 或
1 1 3 2 2 x x 1 2 4 海赛阵= 1 1 1 2 2 x1 x2 4
1 1 1 x1 2 x2 2 4 3 1 1 x12 x2 2 4
1 3 1 D1 x1 2 x22 0 4
D2
1.11.d 1.11.e 1.11.f 计算
仅当 a
1 2
x2 时这才是正的,因而投入要素集并不总是单调的。 x1
查看 f 的海赛阵,其行列式为零,且第一主子式为正。所以 f 不是凹的。 仅 凭这点不足以证明投入要素集不是凸的。但我们可以说得更详细: f 是凸的, 所 以具有下述形式的所有集合都是凸的。 这正是我们感兴趣 {x1 , x 2 : ax1 x1 x 2 bx 2 y} 对所有 y 的选择除了边界点外, 的投入要素集的补集(不等号的方向错了) 。作为凸集的补集(使得边界线不是 一条直线)我们的投入要素集本身因而不能是凸的。 1.11. g 这一函数是一线性与一里昂惕夫函数的连续运用, 所以它具有这两种函 数所拥有的所有性质,包括是正则、单调和凸的。 2.利润最大化 2.1 对于利润最大化,库恩-塔克定理要求下列三个不等式成立
算法导论课程作业答案
算法导论课程作业答案Introduction to AlgorithmsMassachusetts Institute of Technology 6.046J/18.410J Singapore-MIT Alliance SMA5503 Professors Erik Demaine,Lee Wee Sun,and Charles E.Leiserson Handout10Diagnostic Test SolutionsProblem1Consider the following pseudocode:R OUTINE(n)1if n=12then return13else return n+R OUTINE(n?1)(a)Give a one-sentence description of what R OUTINE(n)does.(Remember,don’t guess.) Solution:The routine gives the sum from1to n.(b)Give a precondition for the routine to work correctly.Solution:The value n must be greater than0;otherwise,the routine loops forever.(c)Give a one-sentence description of a faster implementation of the same routine. Solution:Return the value n(n+1)/2.Problem2Give a short(1–2-sentence)description of each of the following data structures:(a)FIFO queueSolution:A dynamic set where the element removed is always the one that has been in the set for the longest time.(b)Priority queueSolution:A dynamic set where each element has anassociated priority value.The element removed is the element with the highest(or lowest)priority.(c)Hash tableSolution:A dynamic set where the location of an element is computed using a function of the ele ment’s key.Problem3UsingΘ-notation,describe the worst-case running time of the best algorithm that you know for each of the following:(a)Finding an element in a sorted array.Solution:Θ(log n)(b)Finding an element in a sorted linked-list.Solution:Θ(n)(c)Inserting an element in a sorted array,once the position is found.Solution:Θ(n)(d)Inserting an element in a sorted linked-list,once the position is found.Solution:Θ(1)Problem4Describe an algorithm that locates the?rst occurrence of the largest element in a?nite list of integers,where the integers are not necessarily distinct.What is the worst-case running time of your algorithm?Solution:Idea is as follows:go through list,keeping track of the largest element found so far and its index.Update whenever necessary.Running time isΘ(n).Problem5How does the height h of a balanced binary search tree relate to the number of nodes n in the tree? Solution:h=O(lg n) Problem 6Does an undirected graph with 5vertices,each of degree 3,exist?If so,draw such a graph.If not,explain why no such graph exists.Solution:No such graph exists by the Handshaking Lemma.Every edge adds 2to the sum of the degrees.Consequently,the sum of the degrees must be even.Problem 7It is known that if a solution to Problem A exists,then a solution to Problem B exists also.(a)Professor Goldbach has just produced a 1,000-page proof that Problem A is unsolvable.If his proof turns out to be valid,can we conclude that Problem B is also unsolvable?Answer yes or no (or don’t know).Solution:No(b)Professor Wiles has just produced a 10,000-page proof that Problem B is unsolvable.If the proof turns out to be valid,can we conclude that problem A is unsolvable as well?Answer yes or no (or don’t know).Solution:YesProblem 8Consider the following statement:If 5points are placed anywhere on or inside a unit square,then there must exist two that are no more than √2/2units apart.Here are two attempts to prove this statement.Proof (a):Place 4of the points on the vertices of the square;that way they are maximally sepa-rated from one another.The 5th point must then lie within √2/2units of one of the other points,since the furthest from the corners it can be is the center,which is exactly √2/2units fromeach of the four corners.Proof (b):Partition the square into 4squares,each with a side of 1/2unit.If any two points areon or inside one of these smaller squares,the distance between these two points will be at most √2/2units.Since there are 5points and only 4squares,at least two points must fall on or inside one of the smaller squares,giving a set of points that are no more than √2/2apart.Which of the proofs are correct:(a),(b),both,or neither (or don’t know)?Solution:(b)onlyProblem9Give an inductive proof of the following statement:For every natural number n>3,we have n!>2n.Solution:Base case:True for n=4.Inductive step:Assume n!>2n.Then,multiplying both sides by(n+1),we get(n+1)n!> (n+1)2n>2?2n=2n+1.Problem10We want to line up6out of10children.Which of the following expresses the number of possible line-ups?(Circle the right answer.)(a)10!/6!(b)10!/4!(c) 106(d) 104 ·6!(e)None of the above(f)Don’t knowSolution:(b),(d)are both correctProblem11A deck of52cards is shuf?ed thoroughly.What is the probability that the4aces are all next to each other?(Circle theright answer.)(a)4!49!/52!(b)1/52!(c)4!/52!(d)4!48!/52!(e)None of the above(f)Don’t knowSolution:(a)Problem12The weather forecaster says that the probability of rain on Saturday is25%and that the probability of rain on Sunday is25%.Consider the following statement:The probability of rain during the weekend is50%.Which of the following best describes the validity of this statement?(a)If the two events(rain on Sat/rain on Sun)are independent,then we can add up the twoprobabilities,and the statement is true.Without independence,we can’t tell.(b)True,whether the two events are independent or not.(c)If the events are independent,the statement is false,because the the probability of no rainduring the weekend is9/16.If they are not independent,we can’t tell.(d)False,no matter what.(e)None of the above.(f)Don’t know.Solution:(c)Problem13A player throws darts at a target.On each trial,independentlyof the other trials,he hits the bull’s-eye with probability1/4.How many times should he throw so that his probability is75%of hitting the bull’s-eye at least once?(a)3(b)4(c)5(d)75%can’t be achieved.(e)Don’t know.Solution:(c),assuming that we want the probability to be≥0.75,not necessarily exactly0.75.Problem14Let X be an indicator random variable.Which of the following statements are true?(Circle all that apply.)(a)Pr{X=0}=Pr{X=1}=1/2(b)Pr{X=1}=E[X](c)E[X]=E[X2](d)E[X]=(E[X])2Solution:(b)and(c)only。
算法导论 第三版 第九章 答案 英
2Hale Waihona Puke is less than roughly 4n/14 of the elements. So, we are never calling it recursively on more than 10n/14 elements. So, T (n) ≤ T (n/7) + T (10n/14) + O(n). So, we can show by substitution this is linear. Suppose T (n) < cn for n < k , then, for m ≥ k , T (m) ≤ T (m/7) + T (10m/14) + O(m) ≤ cm(1/7 + 10/14) + O(m). So, as long as we have that the constant hidden in the big-Oh notation is less than c/7, we have the desired result. Suppose now that we use groups of size 3 instead. So, For similar reasons, we have that the recurrence we are able to get is T (n) = T ( n/3 ) + T (4n/6) + O(n) ≥ T (n/3) + T (2n/3) + O(n). So, we will show it is ≥ cn lg(n). T (m) ≥ c(m/3) lg(m/3) + c(2m/3) lg(2m/3) + O(m) ≥ cm lg(m) + O(m). So, we have that it grows more quickly than linear. Exercise 9.3-2 We know that the number of elements greater than or equal to x and the number of elements less than or equal to x is at least 3n/10 − 6. Then for n ≥ 140 we have 3n/10 − 6 = Exercise 9.3-3 We can modify quicksort to run in worst case n lg(n) time by choosing our pivot element to be the exact median by using quick select. Then, we are guaranteed that our pivot will be good, and the time taken to find the median is on the same order of the rest of the partitioning. Exercise 9.3-4 Create a graph with n vertices and draw a directed edge from vertex i to vertex j if the ith and j th elements of the array are compared in the algorithm and we discover that A[i] ≥ A[j ]. Observe that A[i] is one of the i − 1 smaller elements if there exists a path from x to i in the graph, and A[i] is one of the n − i larger elements if there exists a path from i to x in the graph. Every vertex i must either lie on a path to or from x because otherwise the algorithm can’t distinguish between i ≤ x and i ≥ x. Moreover, if a vertex i lies on both a path to x and a path from x then it must be such that x ≤ A[i] ≤ x, so x = A[i]. In this case, we can break ties arbitrarily. Exercise 9.3-5 To use it, just find the median, partition the array based on that median. If i is less than half the length of the original array, recurse on the first half, if i is half the length of the array, return the element coming from the median finding 3 n n + − 6 ≥ n/4 + 140/20 − 6 = n/4 + 1 ≥ n/4 . 4 20
算法导论第三版第六章答案英
算法导论第三版第六章答案英Chapter6Michelle Bodnar,Andrew LohrDecember31,2016Exercise6.1-1At least2h and at most2h+1?1.Can be seen because a complete binarytree of depth h?1hasΣh?1i=02i=2h?1elements,and the number of elementsin a heap of depth h is between the number for a complete binary tree of depth h?1exclusive and the number in a complete binary tree of depth h inclusive.Exercise6.1-2Write n=2m?1+k where m is as large as possible.Then the heap consists of a complete binary tree of height m?1,along with k additional leaves along the bottom.The height of the root is the length of the longest simple path to one of these kleaves,which must have length m.It is clear from the way we de?ned m that m= lg n .Exercise6.1-3If there largest element in the subtee were somewhere other than the root, it has a parent that is in the subtree.So,it is larger than it’s parent,so,the heap property is violated at the parent of the maximum element in the subtreeExercise6.1-4The smallest element must be a a leaf node.Suppose that node x contains the smallest element and x is not a leaf.Let y denote a child node of x.By the max-heap property,the value of x is greater than or equal to the value of y.Since the elements of the heap are distinct,the inequality is strict.This contradicts the assumption that x contains the smallest element in the heap. Exercise6.1-5Yes,it is.The index of a child is always greater than the index of the parent, so the heap property is satis?ed at each vertex. 1Exercise6.1-6No,the array is not a max-heap.7is contained in position9of the array,so its parent must be in position4,which contains6.This violates the max-heap property.Exercise6.1-7It su?ces to show that the elements with no children are exactly indexed by{ n/2 +1,...,n}.Suppose that we had an i in this range.It’s childeren would be located at2i and2i+1but both of these are≥2 n/2 +2>n and so are not in the array.Now,suppose we had an element with no kids,this means that2i and2i+1are both>n,however,this means that i>n/2.This means that i∈{ n/2 +1,...,n}.Exercise6.2-1271731613101571248902717101613315712489027171016138157124830Exercise6.2-2Algorithm1MIN-HEAPIFY(A,i)1:l=LEF T(i)2:r=RIGHT(i)3:if l≤A.heap?size and A[l]4:smallest=l5:else smallest=i6:end if7:if r≤A.heap?size and A[r]8:smallest=r9:end if10:if smallest=i then11:exchange A[i]with A[smallest]12:MIN-HEAPIFY(A,smallest)13:end ifThe running time of MIN-HEAPIFY is the same as that of MAX-HEAPIFY. Exercise6.2-3The array remains unchanged since the if statement on line line8will be false.2Exercise6.2-4If i>A.heap?size/2then l and r will both exceed A.heap?size so the if statement conditions on lines3and6of the algorithm will never be satis?ed. Therefore largest=i so the recursive call will never be made and nothing will happen.This makes sense because i necessarily corresponds to a leaf node,so MAX–HEAPIFY shouldn’t alter the heap.Exercise6.2-5Iterative Max Heapify(A,i)while il=LEFT(i)r=LEFT(i)largest=iif l≤A.heap-size and A[l]>A[i]thenlargest=lend ifif l≤A.heap-size and A[r]>A[i]thenlargest=rend ifif largest=i thenexchange A[i]and A[largest]elsereturn Aend ifend whilereturn AExercise6.2-6Consider the heap resulting from A where A[1]=1and A[i]=2for 2≤i≤n.Since1is the smallest element of the heap,it must be swapped through each level of the heap until it is a leaf node.Since the heap has height lg n ,MAX-HEAPIFY has worst-case time?(lg n).Exercise6.3-1531710841962295317228419610953192284176109584192231761098451922317610984221953176109842219103176593Exercise6.3-2If we had started at1,we wouldn’t be able to guarantee that the max-heap property is maintained.For example,if the array A is given by[2,1,1,3]then MAX-HEAPIFY won’t exchange2with either of it’s children,both1’s.How-ever,when MAX-HEAPIFY is called on the left child,1,it will swap1with3. This violates the max-heap property because now2is the parent of3.Exercise6.3-3All the nodes of height h partition the set of leaves into sets of size between 2h?1+1and2h,where all but one is size2h.Just by putting all the children of each in their own part of trhe partition.Recall from6.1-2that the heap has height lg(n) ,so,by looking at the one element of this height(the root),we get that there are at most2 lg(n) leaves.Since each of the vertices of height h partitions this into parts of size at least2h?1+1,and all but one corresponds to a part of size2h,we can let k denote the quantity we wish to bound,so,(k?1)2h+k(2h?1+1)≤2 lg(n) ≤n/2sok≤n+2h2h+1+2h+1≤n2h+1≤n2h+1Exercise6.4-14513225717208451320257172845252013717284255201371728425132057172842513208717254413208717252520134871725252013178742525513178742202517135874220252135874172025132587417202513852741720254852713172025845271317202587524131720254752813172025745281317202524578131720255427813172025245781317202542578131720252457813172025Exercise6.4-2We’ll prove the loop invariant of HEAPSORT by induction:Base case:At the start of the?rst iteration of the for loop of lines2-5we have i=A.length.The subarray A[1..n]is a max-heap since BUILD-MAX-HEAP(A)was just called.It contains the n smallest elements,and the empty subarray A[n+1..n]trivially contains the0largest elements of A in sorted order.Suppose that at the start of the i th iteration of of the for loop of lines2-5, the subarray A[1..i]is a max-heap containing the i smallest elements of A[1..n] and the subarray A[i+1..n]contains the n?i largest elements of A[1..n]in sorted order.SinceA[1..i]is a max-heap,A[1]is the largest element in A[1..i]. Thus it is the(n?(i?1))th largest element from the original array since the n?i largest elements are assumed to be at the end of the array.Line3swaps A[1]with A[i],so A[i..n]contain the n?i+1largest elements of the array, and A[1..i?i]contains the i?1smallest elements.Finally,MAX-HEAPIFY is called on A,1.Since A[1..i]was a max-heap prior to the iteration and only the elements in positions1and i were swapped,the left and right subtrees ofnode1,up to node i?1,will be max-heaps.The call to MAX-HEAPIFY will place the element now located at node1into the correct position and restore the5max-heap property so that A[1..i?1]is a max-heap.This concludes the next iteration,and we have veri?ed each part of the loop invariant.By induction, the loop invariant holds for all iterations.After the?nal iteration,the loop invariant says that the subarray A[2..n] contains the n?1largest elements ofA[1..n],sorted.Since A[1]must be the n th largest element,the whole array must be sorted as desired.Exercise6.4-3If it’s already sorted in increasing order,doing the build max heap-max-heap call on line1will takeΘ(n lg(n))time.There will be n iterations of the for loop, each takingΘ(lg(n))time because the element that was at position i was the smallest and so will have lg(n) steps when doing max-heapify on line5.So, it will beΘ(n lg(n))time.If it’s already sorted in decreasing order,then the call on line one will only takeΘ(n)time,since it was already a heap to begin with,but it will still take n lg(n)peel o?the elements from the heap and re-heapify.Exercise6.4-4Consider calling HEAPSORT on an array which is sorted in decreasing order. Every time A[1]is swapped with A[i],MAX-HEAPIFY will be recursively called a number of times equal to the height h of the max-heap containing the elements of positions1through i?1,and has runtime O(h).Since there are2k nodes at height k,the runtime is bounded below bylg ni=12i log(2i)=lg ni=1i2i=2+( lg n ?1)2 lg n =?(n lg n).Exercise6.4-5Since the call on line one could possibly take only linear time(if the input was already a max-heap for example),we will focus on showing that the for loop takes n log n time.This is the case because each time that the last element is placed at the beginning to replace the max element being removed,it has to go through every layer,because it was already very small since it was at the bottom level of the heap before.Exercise6.5-1The following sequence of pictures shows how the max is extracted from the heap.1.Original heap:615 13540126298172.we move the last element to the top of theheap 3.13>9>1so,we swap1and13.4.Since12>5>1,we swap1and12.75.Since6>2>1,we swap1and6.Exercise6.5-2The following sequence of pictures shows how10is inserted into the heap, then swapped with parent nodes until the max-heap property is restored.The node containing the new key is heavily shaded.1.Original heap:815 13540126298172.MAX-HEAP-INSERT(A,10)is called,so we?rst append a node assignedvalue?∞:3.The key value of the new node is updated:4.Since the parent key is smaller than10,the nodes are swapped:95.Since the parent node is smaller than10,the nodes are swapped:Exercise6.5-3Heap-Minimum(A)1:return A[1]Heap-Extract-Min(A)1:if A.heap-size<1then2:Error“heap under?ow”3:end if4:min=A[1]5:A[1]=A[A.heap?size]6:A.heap?size??7:Min-heapify(A,1)8:return minHeap-decrease-key(A,i,key)101:if key?A[i]then2:Error“new key larger than old key”3:end if4:A[i]=key5:while i>1and A[P arent(i)]6:exchange A[i]with A[P arent(i)]7:i=P arent(i)8:end whileMin-Heap-Insert(A,key)1:A.heap?size++2:A[A.heap?size]=∞3:Heap-Decrease-Key(A,A.heap-size,key)Exercise6.5-4If we don’t make an assignment to A[A.heap?size]then it could contain any value.In particular,when we call HEAP-INCREASE-KEY,it might be the case that A[A.heap?size]initially contains a value larger than key,causing an error.By assigning?∞to A[A.heap?size]we guarantee that no error will occur.However,we could have assigned any value less than or equal to key to A[A.heap?size]and the algorithm would still work.Exercise6.5-5Initially,we have a heap and then only change the value at i to make it larger.This can’t invalidate the ordering between i and it’s children,the only other thing that needs to be related to i is that i is less than it’s parent,which may be false.Thus we have the invariant is true at initialization.Then,when we swap i with its parent if it is larger,since it is larger than it’s parent,it must also be larger than it’s sibling,also,since it’s parent was initially above its kids in the heap,we know that it’s parent is larger than it’s kids.The only relation in question is then the new i and it’s parent.At termination,i is the root,so it has no parent,so the heap property must be satis?ed everywhere.Exercise6.5-6Replace A[i]by key in the while condition,and replace line5by“A[i]= A[P ARENT(i)].”After the end of the while loop,add the line A[i]=key. Since the key value doesn’t change,there’s no sense in assigning it until we know where it belongs in the heap.Instead,we only make the assignment of the parent to the child node.At the end of the while loop,i is equal to the position where key belongs since it is either the root,or the parent is at least11key,so we make the assignment.Exercise6.5-7Have a?eld in the structure that is just a count of the total number of elements ever added.When adding an element,use thecurrent value of that counter as the key.Exercise6.5-8The algorithm works as follows:Replace the node to be deleted by the last node of the heap.Update the size of the heap,then call MAX-HEAPIFY to move that node into its proper position and maintain the max-heap property. This has running timeO(lg n)since the number of times MAX-HEAPIFY is recursively called is as most the height of the heap,which is lg n . Algorithm2HEAP-DELETE(A,i)1:A[i]=A[A.heap?size]2:A.heap?size=A.heap?size+13:MAX-HEAPIFY(A,i)Exercise6.5-9Construct a min heap from the heads of each of the k lists.Then,to?nd the next element in the sorted array,extract the minimum element(in O lg(k) time).Then,add to the heap the next element from the shorter list from which the extracted element originally came(also O(lg(k))time).Since?nding the next element in the sorted list takes only at most O(lg(k))time,to? nd the whole list,you need O(n lg(k))total steps.Problem6-1a.They do not.Consider the array A= 3,2,1,4,5 .If we run Build-Max-Heap,we get 5,4,1,3,2 .However,if we run Build-Max-Heap’,we will get 5,4,1,2,3 instead.b.Each insert step takes at most O(lg(n)),since we are doing it n times,weget a bound on the runtime of O(n lg(n)).Problem6-2a.It will su?ce to show how to access parent and child nodes.In a d-ary array,PARENT(i)= i/d ,and CHILD(k,i)=di?d+1+k,where CHILD(k,i) gives the k th child of the node indexed by i.12b.The height of a d-ary heap of n elements is with1of log d n.c.The following is an implementation of HEAP-EXTRACT-MAX for a d-aryheap.An implementation of DMAX-HEAPIFY is also given,which is the analog of MAX-HEAPIFY for d-ary heap.HEAP-EXTRACT-MAX con-sists of constant time operations,followed by a call to DMAX-HEAPIFY.The number of times this recursively calls itself is bounded by the height of the d-ary heap,so the running time is O(d log d n).Note that the CHILD function is meant to be the one described in part(a).Algorithm3HEAP-EXTRACT-MAX(A)for a d-ary heap1:if A.heap?size<1then2:error“heap under?ow”3:end if4:max=A[1]5:A[1]=A[A.heap?size]6:A.heap?size=A.heap?size?17:DMAX-HEAPIFY(A,1)Algorithm4DMAX-HEAPIFY(A,i)1:largest=i2:for k=1to d do3:if CHILD(k,i)≤A.heap?size and A[CHILD(k,i)]>A[i]then4:if A[CHILD(k,i)]>largest then5:largest=A[CHILD(k,i)]6:end if7:end if8:end for9:if largest=i then10:exchange A[i]with A[largest]11:DMAX-HEAPIFY(A,largest)12:end ifd.The runtime of this implementation of INSERT is O(log d n)since the whileloop runs at most as many times as the height of the d-ary array.Note that when we call PARENT,we mean it as de?ned in part(a).e.This is identical to the implementation of HEAP-INCREASE-KEY for2-aryheaps,but with the PARENT function interpreted as in part(a).The run-time is O(log d n)since the while loop runs at most as many times as the height of the d-ary array.13Algorithm5INSERT(A,key)1:A.heap?size=A.heap?size+12:A[A.heap?size]=key3:i=A.heap?size4:while i>1and A[P ARENT(i)5:exchange A[i]with A[P ARENT(i)]6:i=P ARENT(i)7:end whileAlgorithm6INCREASE-KEY(A,i,key)1:if key2:error“new key is smaller than current key”3:end if4:A[i]=key5:while i>1and A[P ARENT(i)6:exchange A[i]with A[P ARENT(i)]7:i=P ARENT(i)8:end whileProblem6-3a.2345 891214 16∞∞∞∞∞∞∞b.For every i,j,Y[1,1]≤Y[i,1]≤Y[i,j].So,if Y[1,1]=∞,we know thatY[i,j]=∞for every i,j.This means that no elements exist.If Y is full,it has no elements labeled∞,in particular,the element Y[m,n]is not labeled ∞.c.Extract-Min(Y,i,j),extracts the minimum value from the young tableau Yobtained by Y [i ,j ]=Y[i +i?1,j +j?1].Note that in running this algorithm,several accesses may be made out of bounds for Y,de? ne these to return∞.No store operations will be made on out of bounds locations.Since the largest value of i+j that this can be called with is n+m,and this quantity must increase by one for each call,we have that the runtime is bounded by n+m.d.Insert(Y,key)Since i+j is decreasing at each step,starts as n+m and isbounded by2below,we know that this program has runtime O(n+m). e.Place the n2elements into a Young Tableau by calling the algorithm frompart d on each.Then,call the algorithm from part c n2to obtain the numbers in increasing order.Both of these operations take time at most2n∈O(n), and are done n2times,so,the total runtime is O(n3)141:min=Y[i,j]2:if Y[i,j+1]=Y[i+1,j]=∞then3:Y[i,j]=∞4:return min5:end if6:if Y[i,j+1]7:Y[i,j]=Y[i,j+1]8:Y[i,j+1]=min9:return Extract-min(y,i,j+1)10:else11:Y[i,j]=Y[i+1,j]12:Y[i+1,j]=min13:return Extract-min(y,i+1,j)14:end if1:i=m,j=n2:Y[i,j]=key3:while Y[i?1,j]>Y[i,j]or Y[i,j?1]>Y[i,j]do 4:if Y[i?1,j]5:Swap Y[i,j]and Y[i,j?1]6:j??7:else8:Swap Y[i,j]and Y[i?1,j]9:i??10:end if11:end while15f.Find(Y,key).Let Check(y,key,i,j)mean to return true if Y[i,j]=key,oth-erwise do nothingi=j=1while Y[i,j]Check(Y,key,i,j)i++end whilewhile i>1and jCheck(i,j)if Y[i,j]j++elsei–end ifend whilereturn false16。
Ch10算法导论 第三版 第十章 答案 英
Chapter10Michelle Bodnar,Andrew LohrApril12,2016Exercise10.1-14414134141841Exercise10.1-2We will call the stacks T and R.Initially,set T.top=0and R.top=n+1. Essentially,stack T uses thefirst part of the array and stack R uses the last part of the array.In stack T,the top is the rightmost element of T.In stack R, the top is the leftmost element of R.Algorithm1PUSH(S,x)1:if S==T then2:if T.top+1==R.top then3:error“overflow”4:else5:T.top=T.top+16:T[T.top]=x7:end if8:end if9:if S==R then10:if R.top−1==T.top then11:error“overflow”12:else13:R.top=R.top−114:T[T.top]=x15:end if16:end if1Algorithm2POP(S)if S==T thenif T.top==0thenerror“underflow”elseT.top=T.top−1.return T[T.top+1]end ifend ifif S==R thenif R.top==n+1thenerror“underflow”elseR.top=R.top+1.return R[R.top−1]end ifend ifExercise10.1-34414131313838Exercise10.1-4Algorithm3ENQUEUEif Q.head==Q.tail+1,or Q.head==1and Q.tail==Q.length then error“overflow”end ifQ[Q.tail]=xif Q.tail==Q.length thenQ.tail=1elseQ.tail=Q.head+1end ifExercise10.1-5As in the example code given in the section,we will neglect to check for overflow and underflow errors.2Algorithm4DEQUEUEerror“underflow”end ifx=Q[Q.head]if Q.head==Q.length thenQ.head=1elseQ.head=Q.head+1end ifreturn xAlgorithm5HEAD-ENQUEUE(Q,x) Q[Q.head]=xif Q.head==1thenQ.head=Q.lengthelseQ.head=Q.head−1end ifAlgorithm6TAIL-ENQUEUE(Q,x) Q[Q.tail]=xif Q.tail==Q.length thenQ.tail=1elseQ.tail=Q.tail+1end ifAlgorithm7HEAD-DEQUEUE(Q,x) x=Q[Q.head]if Q.head==Q.length thenQ.head=1elseQ.head=Q.head+1end ifAlgorithm8TAIL-DEQUEUE(Q,x) x=Q[Q.tail]if Q.tail==1thenQ.tail=Q.lengthelseQ.tail=Q.tail−1end if3Exercise10.1-6The operation enqueue will be the same as pushing an element on to stack 1.This operation is O(1).To dequeue,we pop an element from stack2.If stack 2is empty,for each element in stack1we pop it off,then push it on to stack2. Finally,pop the top item from stack2.This operation is O(n)in the worst case.Exercise10.1-7The following is a way of implementing a stack using two queues,where pop takes linear time,and push takes constant time.Thefirst of these ways,consists of just enqueueing each element as you push it.Then,to do a pop,you dequque each element from one of the queues and place it in the other,but stopping just before the last element.Then,return the single element left in the original queue.Exercise10.2-1To insert an element in constant time,just add it to the head by making it point to the old head and have it be the head.To delete an element,it needs linear time because there is no way to get a pointer to the previous element in the list without starting at the head and scanning along.Exercise10.2-2The PUSH(L,x)operation is exactly the same as LIST-INSERT(L,x).The POP operation sets x equal to L.head,calls LIST-DELETE(L,L.head),then returns x.Exercise10.2-3In addition to the head,also keep a pointer to the last element in the linked list.To enqueue,insert the element after the last element of the list,and set it to be the new last element.To dequeue,delete thefirst element of the list and return it.Exercise10.2-4First let L.nil.key=k.Then run LIST-SEARCH’as usual,but remove the check that x=L.nil.Exercise10.2-5To insert,just do list insert before the current head,in constant time.To search,start at the head,check if the element is the current node being in-spected,check the next element,and so on until at the end of the list or you4found the element.This can take linear time in the worst case.To delete,again linear time is used because there is no way to get to the element immediately before the current element without starting at the head and going along the list.Exercise10.2-6Let L1be a doubly linked list containing the elements of S1and L2be a doubly linked list containing the elements of S2.We implement UNION as fol-lows:Set L1.nil.prev.next=L2.nil.next and L2.nil.next.prev=L1.nil.prev so that the last element of L1is followed by thefirst element of L2.Then set L1.nil.prev=L2.nil.prev and L2.nil.prev.next=L1.nil,so that L1.nil is the sentinel for the doubly linked list containing all the elements of L1and L2. Exercise10.2-7Algorithm9REVERSE(L)a=L.head.nextb=L.headwhile a=NIL dotmp=a.nexta.next=bb=aa=tmpend whileL.head=bExercise10.2-8We will store the pointer value for L.head separately,for convenience.In general,A XOR(A XOR C)=C,so once we know one pointer’s true value we can recover all the others(namely L.head)by applying this rule.Assuming there are at least two elements in the list,thefirst element will contain exactly the address of the second.Algorithm10LISTnp-SEARCH(L,k)p=NILx=L.headwhile x=NIL and x.key=k dotemp=xx=pXORx.npp=tempend whileTo reverse the list,we simply need to make the head be the“last”ele-5Algorithm11LISTnp-INSERT(L,x)x.np=L.headL.nil.np=xXOR(L.nil.npXORL.head)L.head=xAlgorithm12LISTnp-Delete(L,x)L.nil.np=L.nil.npXORL.headXORL.head.npL.head.np.np=L.head.np.npXORL.headment before L.nil instead of thefirst one after this.This is done by settingL.head=L.nil.npXORL.head.Exercise10.3-1A multiple array version could be L=2,/34567/124819511/23456A single array version could be L=4,127/410481371916105191311/16 Exercise10.3-2Algorithm13Allocate-Object()if free==NIL thenerror“out of space”elsex=freefree=A[x+1]end ifExercise10.3-3Allocate object just returns the index of some cells that it’s guaranteed tonot give out again until they’ve been freed.The prev attribute is not modified because only the next attribute is used by the memory manager,it’s up to the code that calls allocate to use the prev and key attributes as it seesfit.Exercise10.3-4For ALLOCATE-OBJECT,we will keep track of the next available spot inthe array,and it will always be one greater than the number of elements being stored.For FREE-OBJECT(x),when a space is freed,we will decrement the6Algorithm14Free-Object(x)A[x+1]=freefree=xposition of each element in a position greater than that of x by1and update pointers accordingly.This takes linear time.Exercise10.3-5See the algorithm COMP ACT IF Y−LIST(L,F)Exercise10.4-1181274510221Note that indices8and2in the array do not appear,and,in fact do not represent a valid tree.Exercise10.4-2See the algorithm PRINT-TREE.Exercise10.4-3Exercise10.4-4See the algorithm PRINT-TREE.Exercise10.4-5See the algorithm INORDER-PRINT’(T)Exercise10.4-6Our two pointers will be left and right.For a node x,x.left will point to the leftmost child of x and x.right will point to the sibling of x immediately to its right,if it has one,and the parent of x otherwise.Our boolean value b,stored at x,will be such that b=depth(x)mod2.To reach the parent of a node, simply keep following the“right”pointers until the parity of the boolean value changes.Tofind all the children of a node,start byfinding x.left,then follow7Algorithm15COMPACTIFY-LIST(L,F)if n=m thenreturnend ife=max{max i∈[m]{|key[i]|},max i∈L{|key[i]|}}increase every element of key[1..m]by2efor every element of L,if its key is greater than e,reduce it by2e f=1while key[f]<e dof++end whilea=L.headif a>m thennext[prev[f]]=next[f]prev[next[f]]=prev[f]next[f]=next[a]key[f]=key[a]prev[f]=prev[a]F REE−OBJECT(a)f++while key[f]<e dof++end whileend ifwhile a=L.head doif a>m thennext[prev[f]]=next[f]prev[next[f]]=prev[f]next[f]=next[a]key[f]=key[a]prev[f]=prev[a]F REE−OBJECT(a)f++while key[f]<e dof++end whileend ifend while8Algorithm16PRINT-TREE(T.root) if T.root==NIL thenreturnelsePrint T.root.keyPRINT-TREE(T.root.left)PRINT-TREE(T.root.right)end ifAlgorithm17INORDER-PRINT(T) let S be an empty stackpush(S,T)while S is not empty doU=pop(S)if U=NIL thenprint U.keypush(S,U.left)push(S,U.right)end ifend whileAlgorithm18PRINT-TREE(T.root) if T.root==NIL thenreturnelsePrint T.root.keyx=T.root.left−childwhile x=NIL doPRINT-TREE(x)x=x.right−siblingend whileend if9Algorithm19INORDER-PRINT’(T) a=T.leftprev=Twhile a=T doif prev=a.left thenprint a.keyprev=aa=a.rightelse if prev=a.right thenprev=aa=a.pelse if prev=a.p thenprev=aa=a.leftend ifend whileprint T.keya=T.rightwhile a=T doif prev=a.left thenprint a.keyprev=aa=a.rightelse if prev=a.right thenprev=aa=a.pelse if prev=a.p thenprev=aa=a.leftend ifend while10the“right”pointers until the parity of the boolean value changes,ignoring thislast node since it will be x.Problem10-1For each,we assume sorted means sorted in ascending orderunsorted,single sorted,single unsorted,double sorted,double SEARCH(L,k)n n n nINSERT(L,x)1111DELET E(L,x)n n11SUCCESSOR(L,x)n1n1P REDECESSOR(L,x)n n n1 MINIMUM(L,x)n1n1MAXIMUM(L,x)n n n1 Problem10-2In all three cases,MAKE-HEAP simply creates a new list L,sets L.head=NIL,and returns L in constant time.Assume lists are doubly linked.To realizea linked list as a heap,we imagine the usual array implementation of a binaryheap,where the children of the i th element are2i and2i+1.a.To insert,we perform a linear scan to see where to insert an element suchthat the list remains sorted.This takes linear time.Thefirst element in thelist is the minimum element,and we canfind it in constant time.Extract-minreturns thefirst element of the list,then deletes it.Union performs a mergeoperation between the two sorted lists,interleaving their entries such thatthe resulting list is sorted.This takes time linear in the sum of the lengthsof the two lists.b.To insert an element x into the heap,begin linearly scanning the list untilthefirst instance of an element y which is strictly larger than x.If no suchlarger element exists,simply insert x at the end of the list.If y does exist,replace y t by x.This maintains the min-heap property because x≤y andy was smaller than each of its children,so x must be as well.Moreover,xis larger than its parent because y was thefirst element in the list to exceedx.Now insert y,starting the scan at the node following x.Since we checkeach node at most once,the time is linear in the size of the list.To get theminimum element,return the key of the head of the list in constant time.To extract the minimum element,wefirst call MINIMUM.Next,we’ll replacethe key of the head of the list by the key of the second smallest element yin the list.We’ll take the key stored at the end of the list and use it toreplace the key of y.Finally,we’ll delete the last element of the list,and callMIN-HEAPIFY on the list.To implement this with linked lists,we need tostep through the list to get from element i to element2i.We omit this detailfrom the code,but we’ll consider it for runtime analysis.Since the value ofi on which MIN-HEAPIFY is called is always increasing and we never need11to step through elements multiple times,the runtime is linear in the length of the list.Algorithm20EXTRACT-MIN(L)min=MINIMUM(L)Linearly scan for the second smallest element,located in position i.L.head.key=L[i]L[i].key=L[L.length].keyDELETE(L,L[L.length])MIN-HEAPIFY(L[i],i)return minAlgorithm21MIN-HEAPIFY(L[i],i)1:l=L[2i].key2:r=L[2i+1].key3:p=L[i].key4:smallest=i5:if L[2i]=NIL and l<p then6:smallest=2i7:end if8:if L[2i+1]=NIL and r<L[smallest]then9:smallest=2i+110:end if11:if smallest=i then12:exchange L[i]with L[smallest]13:MIN-HEAPIFY(L[smallest],smallest)14:end ifUnion is implemented below,where we assume A and B are the two list representations of heaps to be merged.The runtime is again linear in the lengths of the lists to be merged.c.Since the algorithms in part b didn’t depend on the elements being distinct,we can use the same ones.Problem10-3a.If the original version of the algorithm takes only t iterations,then,we havethat it was only at most t random skips though the list to get to the desired value,since each iteration of the original while loop is a possible random jump followed by a normal step through the linked list.b.The for loop on lines2-7will get run exactly t times,each of which is constantruntime.After that,the while loop on lines8-9will be run exactly X t times.So,the total runtime is O(t+E[X t]).12Algorithm22UNION(A,B)1:if A.head=NIL then2:return B3:end if4:i=15:x=A.head6:while B.head=NIL do7:if B.head.key≤x.key then8:Insert a node at the end of list B with key x.key 9:x.key=B.head.key10:Delete(B,B.head)11:end if x=x.next12:end while13:return Aing equation C.25,we have that E[X t]= ∞i=1P r(X t≥i).So,we needto show that P r(X t≥i)≤(1−i/n)t.This can be seen because having X t being greater than i means that each random choice will result in an element that is either at least i steps before the desired element,or is after the desired element.There are n−i such elements,out of the total n elements that we were pricking from.So,for a single one of the choices to be from such a range, we have a probability of(n−i)/n=(1−i/n).Since each of the selections was independent,the total probability that all of them were is(1−i/n)t, as stly,we can note that since the linked list has length n,the probability that X t is greater than n is equal to zero.d.Since we have that t>0,we know that the function f(x)=x t is increasing,so,that means that x t≤f(x).So,n−1r=0r t=nr t dr≤nf(r)dr=n t+1e.E[X t]≤nr=1(1−r/n)t=nr=1ti=0ti(−r/n)i=ti=0nr=1ti(−r/n)i=ti=0ti(−1)in i−1+n−1r=0(r)t/n≤ti=0ti(−1)in i−1+n i+1/n ≤ti=0ti(−1)in ii+1=1t+1ti=0t+1i+1(−n)i≤(1−n)t+1t+1f.We just put together parts b and e to get that it runs in time O(t+n/(t+1)).But,this is the same as O(t+n/t).13g.Since we have that for any number of iterations t that the first algorithm takes to find its answer,the second algorithm will return it in time O (t +n/t ).In particular,if we just have that t =√n .The second algorithm takestime only O (√n ).This means that tihe first list search algorithm is O (√n )as well.h.If we don’t have distinct key values,then,we may randomly select an element that is further along than we had been before,but not jump to it because it has the same key as what we were currently at.The analysis will break when we try to bound the probability that X t ≥i .14。
算法导论(第二版)习题答案(英文版)
Last update: December 9, 2002
1.2 − 2 Insertion sort beats merge sort when 8n2 < 64n lg n, ⇒ n < 8 lg n, ⇒ 2n/8 < n. This is true for 2 n 43 (found by using a calculator). Rewrite merge sort to use insertion sort for input of size 43 or less in order to improve the running time. 1−1 We assume that all months are 30 days and all years are 365.
n
Θ
i=1
i
= Θ(n2 )
This holds for both the best- and worst-case running time. 2.2 − 3 Given that each element is equally likely to be the one searched for and the element searched for is present in the array, a linear search will on the average have to search through half the elements. This is because half the time the wanted element will be in the first half and half the time it will be in the second half. Both the worst-case and average-case of L INEAR -S EARCH is Θ(n). 3
高级英语(第三版)第一册 练习答案 Lesson 7 Key
《高级英语》(第三版)重排版(第一册)Lesson 7 Everyday UseKey to ExercisesIII. Paraphrase1. She thinks that her sister has a firm control of her life and that she can always have anything she wants.2. Because I am fat, I feel hot even in freezing weather.3. Johnny Carson has a witty and glib tongue. But I outdo him and so he has to try hard if he wants to catch up with me.4. I’m ready to leave as quickly as possible because of discomfort,nervousness, timidity, etc., and turn my head away from them in order to avoid them as much as possible for the same reason.5. She would always look at somebody directly and steadily, not feeling embarrassed or ashamed.6. She imposed on us lots of falsity and so-called knowledge that was totally useless and irrelevant to us.7. She was homely and poor. Besides she was not smart.8. Meanwhile Dee’s boyfriend is trying to shake hands with Maggie in a fancy and elaborate way.9. In fact, I could have traced it back before the Civil War through the family branches.10. He just stood there with a grin on his face and looked at me as if inspecting something old and out-of-date.11. Now and then he and Dee communicated through eye contact in a secretive way.12. I don’t need the quilts to remind me of Grandma Dee. She lives in m y memory. IV. Practice with Words and ExpressionsA.1. extended: enlarged by a new addition to the original space2. homely: plain-looking3. make: to achieve something, to become successful4. tacky: cheap-looking, of bad quality5. overalls: loose-fitting trousers of some strong cotton-cloth, often with a part extending up over the chest, worn, usually over other clothes, to protect against dirt and wear6. fuller: rounded or large in an attractive way7. make-believe: a state of imagining or pretending something is real; falsity8. stare down: to stare back at another until the gaze of the one stared at is turned away9. rawhide: untanned or partially tanned cattle hide10. washday: a day, often the same day every week, when the clothes, linens, etc. of a household are washed11. well-turned: carefully expressed12. loud: attracting attention by being unpleasantly colorful and bright13. salt-lick: a block of rock salt placed in a pasture for cattle, etc. to lick14. talk a blue streak: to talk much and rapidly15. centerpiece: an ornament, like a bowl of flowers, placed in the center of a table16. portion: lot, fateB.1. Dee, however, is not like me.2. And there was Dee.3. It was like the reaction you have when you see the wriggling end of a snake just in front of your foot on the road.4. She is wearing a dress long enough to touch the ground in spite of this5. Her earrings are gold, too, and they are hanging down to her shoulders.6. “No, mama,” she says, “My name is not Dee anymore. It has been changed to Wangero Leewanika Kemanjo!”7. Those people were always too busy with feeding the cattle, fixing the fences, putting up salt-lick shelters, throwing down the hay, etc.8. In the q uilt there were bits and pieces of Grandpa Jarrell’s Paisley shirts.9. The quilts would be in even worse condition than rags.10. She smiled a real smile from the bottom of her heart without any shadow of mental suffering.C.1. I am the way my daughter would want me to be:...my complexion had a smooth and creamy texture.2. Impressed with her they worshiped her well-turned phrases, the cute shape, and the quick humor like something very hot that hurt people.3. He wasted no time in marrying a contemptible city girl from a family of ignorant ostentatious and vulgar people.4. And she stops and moves her toe in the sand because she feels great discomfort.5. Maggie’s hand is limp, lacking firmness, and very cold, too.6. “Maggie’s memory is very good,” Wangero said, laughing.7. “Mama,” Wangero said in an extremely sweet voice.8. She breathed suddenly in painful surprise.9. For us colored people, this is a new era, and we must seize our opportunities.V. TranslationA.1. A big fire burned to the ground more than 300 homes in the slum neighborhood.2. If you are upright and not afraid of losing anything, you will be able to look anyone in the eye.3. This blouse doesn’t match the color or the style of the skirt.4. Let’s talk about the matter over a cup of coffee.5. He couldn’t imagine why people were opposed to his views.6. Stepping out of a car the official was confronted by two terrorists.7. As long as we stick to these principles, we will surely succeed.8. She was shocked at the news, but before long she recomposed herself.9. It’s hard to trace the origin of the reference.B.1. 我在院子里等她来。
新视野大学英语第三版第一册读写教程课后答案unit7
新视野大学英语第三版第一册读写教程课后答案unit7新视野大学英语1第三版读写教程答案Unit 7Section ALanguage focusWords in use31 reveal2 implying3 accurate4 exaggerated5 eliminate6 facilitate7 frustrated8 appropriate9 conscious 10 launch Words building4Words learned New words formed-alcontinue continualemotional emotioinindustry industrialpart partial-encecorrespond correspondenceinnocence innocentpresent presenceoccur occurrenceintelligent intelligence-yworth worthyunite unityinquiry inquire51 correspondence2 continual3 partial4 emotion5 occurrences6 innocent7 worthy 8 industrial 9 presence 10 inquire 11 unity 12 intelligence Banked cloze61 L2 M3 C4 E5 H6 G7 J8 I9 N 10 A Expressions in use71 not to mention2 turn in3 rip off4 cope with5 launched a campaign6 If this/that is the case7 be confined to8 descend intoStructured writing9My dorm is nice to live in. For example, it has a very convenient location. It is close to everything on campus. It only takes 5 minutes to walk to my classes, 8 minutes to the library, 15 minutes to the swimming poo l, and only 2 minutes to the cafeteria. What’s more, there are great facilities in the building. There is a laundry room, a gym, a TV room, and even an ATM machine. Most importantly, I like my roommates. We get along very well, and we have a lot of fun together. In one word, I love my dorm.Translation10在所有美国人的信念中,最基本、最强烈的信念可能就是崇尚个人自由。
Ch10算法导论第三版第十章答案英
Ch10算法导论第三版第十章答案英Chapter10Michelle Bodnar,Andrew LohrApril12,2016Exercise10.1-14414134141841Exercise10.1-2We will call the stacks T and R.Initially,set T.top=0and R.top=n+1. Essentially,stack T uses the?rst part of the array and stack R uses the last part of the array.In stack T,the top is the rightmost element of T.In stack R, the top is the leftmost element of R.Algorithm1PUSH(S,x)1:if S==T then2:if T.top+1==R.top then3:error“over?ow”4:else5:T.top=T.top+16:T[T.top]=x7:end if8:end if9:if S==R then10:if R.top?1==T.top then11:error“over?ow”12:else13:R.top=R.top?1 14:T[T.top]=x 15:end if16:end if1Algorithm2POP(S) if S==T thenif T.top==0then error“under?ow”elseT.top=T.top?1. return T[T.top+1] end ifend ifif S==R thenif R.top==n+1then error“under?ow”elseR.top=R.top+1. return R[R.top?1] end ifend ifExercise10.1-34414131313838Exercise10.1-4Algorithm3ENQUEUEif Q.head==Q.tail+1,or Q.head==1and Q.tail==Q.length then error“over?ow”end ifQ[Q.tail]=xif Q.tail==Q.length thenQ.tail=1elseQ.tail=Q.head+1end ifExercise10.1-5As in the example code given in the section,we will neglect to check for over?ow and under?ow errors.2Algorithm4DEQUEUEerror“under?ow”end ifx=Q[Q.head]if Q.head==Q.length thenQ.head=1elseQ.head=Q.head+1end ifreturn xAlgorithm5HEAD-ENQUEUE(Q,x) Q[Q.head]=xif Q.head==1thenQ.head=Q.lengthelseQ.head=Q.head?1end ifAlgorithm6TAIL-ENQUEUE(Q,x) Q[Q.tail]=xif Q.tail==Q.length thenQ.tail=1elseQ.tail=Q.tail+1end ifAlgorithm7HEAD-DEQUEUE(Q,x) x=Q[Q.head]if Q.head==Q.length thenQ.head=1elseQ.head=Q.head+1end ifAlgorithm8TAIL-DEQUEUE(Q,x) x=Q[Q.tail]if Q.tail==1thenQ.tail=Q.lengthelseQ.tail=Q.tail?1end if3Exercise10.1-6The operation enqueue will be the same as pushing an element on to stack 1.This operation is O(1).To dequeue,we pop an element from stack2.If stack 2is empty,for each element in stack1we pop it o?,then push it on to stack2. Finally,pop the top item from stack2.This operation is O(n)in the worst case.Exercise10.1-7The following is a way of implementing a stack using two queues,where pop takes linear time,and push takes constant time.The?rst of these ways,consists of just enqueueing eachelement as you push it.Then,to do a pop,you dequque each element from one of the queues and place it in the other,but stopping just before the last element.Then,return the single element left in the original queue.Exercise10.2-1To insert an element in constant time,just add it to the head by making it point to the old head and have it be the head.To delete an element,it needs linear time because there is no way to get a pointer to the previous element in the list without starting at the head and scanning along.Exercise10.2-2The PUSH(L,x)operation is exactly the same as LIST-INSERT(L,x).The POP operation sets x equal to L.head,calls LIST-DELETE(L,L.head),then returns x.Exercise10.2-3In addition to the head,also keep a pointer to the last element in the linked list.To enqueue,insert the element after the last element of the list,and set it to be the new last element.T o dequeue,delete the?rst element of the list and return it.Exercise10.2-4First let L.nil.key=k.Then run LIST-SEARCH’as usual,but remove the check that x=L.nil.Exercise10.2-5To insert,just do list insert before the current head,in constant time.To search,start at the head,check if the element is the current node being in-spected,check the next element,and so on until at the end of the list or you4found the element.This can take linear time in the worst case.To delete,again linear time is used because there is no wayto get to the element immediately before the current element without starting at the head and going along the list.Exercise10.2-6Let L1be a doubly linked list containing the elements of S1and L2be a doubly linked list containing the elements of S2.We implement UNION as fol-lows:Set L1.nil.prev.next=L2.nil.next and L2.nil.next.prev=L1.nil.prev so that the last element of L1is followed by the?rst element of L2.Then set L1.nil.prev=L2.nil.prev and L2.nil.prev.next=L1.nil,so that L1.nil is the sentinel for the doubly linked list containing all the elements of L1and L2. Exercise10.2-7Algorithm9REVERSE(L)a=L.head.nextb=L.headwhile a=NIL dotmp=a.nexta.next=bb=aa=tmpend whileL.head=bExercise10.2-8We will store the pointer value for L.head separately,for convenience.In general,A XOR(A XOR C)=C,so once we know one pointer’s true value we can recover all the others(namely L.head)by applying this rule.Assuming there are at least two elements in the list,the?rst element will contain exactly the address of the second.Algorithm10LISTnp-SEARCH(L,k)p=NILx=L.headwhile x=NIL and x.key=k dotemp=xx=pXORx.npp=tempend whileTo reverse the list,we simply need to make the head be the“last”ele-5Algorithm11LISTnp-INSERT(L,x)x.np=L.headL.nil.np=xXOR(L.nil.npXORL.head)L.head=xAlgorithm12LISTnp-Delete(L,x)L.nil.np=L.nil.npXORL.headXORL.head.npL.head.np.np=L.head.np.npXORL.headment before L.nil instead of the?rst one after this.This is done by settingL.head=L.nil.npXORL.head.Exercise10.3-1A multiple array version could be L=2,/34567/124819511/23456A single array version could be L=4,127/410481371916105191311/16 Exercise10.3-2Algorithm13Allocate-Object()if free==NIL thenerror“out of space”elsex=freefree=A[x+1]end ifExercise10.3-3Allocate object just returns the index of some cells that it’s guaranteed tonot give out again until they’ve been freed.The prev attribute is not modi?ed because only the next attribute is used by the memory manager,it’s up to the code that calls allocate to use the prev and key attributes as it sees?t.Exercise10.3-4For ALLOCATE-OBJECT,we will keep track of the next available spot inthe array,and it will always be one greater than the number of elements being stored.For FREE-OBJECT(x),when a space is freed,we will decrement the6Algorithm14Free-Object(x)A[x+1]=freefree=xposition of each element in a position greater than that of x by1and update pointers accordingly.This takes linear time.Exercise10.3-5See the algorithm COMP ACT IF Y?LIST(L,F)Exercise10.4-1181274510221Note that indices8and2in the array do not appear,and,in fact do not represent a valid tree.Exercise10.4-2See the algorithm PRINT-TREE.Exercise10.4-3Exercise10.4-4See the algorithm PRINT-TREE.Exercise10.4-5See the algorithm INORDER-PRINT’(T)Exercise10.4-6Our two pointers will be left and right.For a node x,x.left will point to the leftmost child of x and x.right will point to the sibling of x immediately to its right,if it has one,and the parent of x otherwise.Our boolean value b,stored at x,will be such that b=depth(x)mod2.T o reach the parent of a node, simply keep following the“right”pointers until the parity of the boolean value changes.To?nd all the children of a node,start by?nding x.left,then follow7Algorithm15COMPACTIFY-LIST(L,F)if n=m thenreturnend ife=max{max i∈[m]{|key[i]|},max i∈L{|key[i]|}}increase every element of key[1..m]by2efor every element of L,if its key is greater than e,reduce it by2e f=1while key[f]<="" p="">f++end whilea=L.headif a>m thennext[prev[f]]=next[f]prev[next[f]]=prev[f]next[f]=next[a]key[f]=key[a]prev[f]=prev[a]F REE?OBJECT(a)f++while key[f]<="" p="">f++end whileend ifwhile a=L.head doif a>m thennext[prev[f]]=next[f]prev[next[f]]=prev[f]next[f]=next[a]key[f]=key[a]prev[f]=prev[a]F REE?OBJECT(a)f++while key[f]<="" p="">f++end whileend ifend while8Algorithm16PRINT-TREE(T.root) if T.root==NIL thenreturnelsePrint T.root.keyPRINT-TREE(T.root.left)PRINT-TREE(T.root.right)end ifAlgorithm17INORDER-PRINT(T) let S be an empty stack push(S,T)while S is not empty doU=pop(S)if U=NIL thenprint U.keypush(S,U.left)push(S,U.right)end ifend whileAlgorithm18PRINT-TREE(T.root) if T.root==NIL then returnelsePrint T.root.keyx=T.root.left?childwhile x=NIL doPRINT-TREE(x)x=x.right?siblingend whileend if9Algorithm19INORDER-PRINT’(T) a=T.leftprev=Twhile a=T doif prev=a.left thenprint a.keyprev=aa=a.rightelse if prev=a.right thenprev=aa=a.pelse if prev=a.p thenprev=aa=a.leftend ifend whileprint T.keya=T.rightwhile a=T doif prev=a.left thenprint a.keyprev=aa=a.rightelse if prev=a.right thenprev=aa=a.pelse if prev=a.p thenprev=aa=a.leftend ifend while10the“right”pointers until the parity of the boolean value changes,ignoring thislast node since it will be x.Problem10-1For each,we assume sorted means sorted in ascending order unsorted,single sorted,single unsorted,double sorted,double SEARCH(L,k)n n n nINSERT(L,x)1111DELET E(L,x)n n11SUCCESSOR(L,x)n1n1P REDECESSOR(L,x)n n n1 MINIMUM(L,x)n1n1MAXIMUM(L,x)n n n1 Problem10-2In all three cases,MAKE-HEAP simply creates a new list L,sets L.head=NIL,and returns L in constant time.Assume lists are doubly linked.T o realizea linked list as a heap,we imagine the usual array implementation of a binaryheap,where the children of the i th element are2i and2i+1.a.To insert,we perform a linear scan to see where to insert an element suchthat the list remains sorted.This takes linear time.The?rst element in thelist is the minimum element,and we can?nd it in constant time.Extract-minreturns the?rst element of the list,then deletes it.Union performs a mergeoperation between the two sorted lists,interleaving their entries such thatthe resulting list is sorted.This takes time linear in the sum of the lengthsof the two lists.b.To insert an element x into the heap,begin linearly scanning the list untilthe?rst instance of an element y which is strictly larger than x.If no suchlarger element exists,simply insert x at the end of the list.If y does exist,replace y t by x.This maintains the min-heap property because x≤y andy was smaller than each of its children,so x must be as well.Moreover,xis larger than its parent because y was the?rst element in the list to exceedx.Now insert y,starting the scan at the node following x.Since we checkeach node at most once,the time is linear in the size of the list.To get theminimum element,return the key of the head of the list in constant time.To extract the minimum element,we?rst call MINIM UM.Next,we’ll replacethe key of the head of the list by the key of the second smallest element yin the list.We’ll take the key stored at the end of the list and use it toreplace the key of y.Finally,we’ll delete the last element of the list,and callMIN-HEAPIFY on the list.T o implement this with linked lists,we need tostep through the list to get from element i to element2i.We omit this detailfrom the code,but we’ll consider it for runtime analysis.Since the value ofi on which MIN-HEAPIFY is called is always increasing and we never need11to step through elements multiple times,the runtime is linear in the length of the list.Algorithm20EXTRACT-MIN(L)min=MINIMUM(L)Linearly scan for the second smallest element,located in position i.L.head.key=L[i]L[i].key=L[L.length].keyDELETE(L,L[L.length])MIN-HEAPIFY(L[i],i)return minAlgorithm21MIN-HEAPIFY(L[i],i)1:l=L[2i].key2:r=L[2i+1].key3:p=L[i].key4:smallest=i5:if L[2i]=NIL and l6:smallest=2i7:end if8:if L[2i+1]=NIL and r<l[smallest]then< bdsfid="416" p=""></l[smallest]then<>9:smallest=2i+110:end if11:if smallest=i then12:exchange L[i]with L[smallest]13:MIN-HEAPIFY(L[smallest],smallest)14:end ifUnion is implemented below,where we assume A and B are the two list representations of heaps to be merged.The runtime is again linear in the lengths of the lists to be merged.c.Since the algorithms in part b didn’t depend on the elements being distinct,we can use the same ones.Problem10-3a.If the original version of the algorithm takes only t iterations,then,we havethat it was only at most t random skips though the list to get to the desired value,since each iteration of the original while loop is a possible random jump followed by a normal step through the linked list.b.The for loop on lines2-7will get run exactly t times,each of which is constantruntime.After that,the while loop on lines8-9will be run exactly X t times.So,the total runtime is O(t+E[X t]).12Algorithm22UNION(A,B)1:if A.head=NIL then2:return B3:end if4:i=15:x=A.head6:while B.head=NIL do7:if B.head.key≤x.key then8:Insert a node at the end of list B with key x.key9:x.key=B.head.key10:Delete(B,B.head)11:end if x=x.next12:end while13:return A/doc/8010751696.html,ing equation C.25,we have that E[X t]= ∞i=1P r(X t≥i).So,we needto show that P r(X t≥i)≤(1?i/n)t.This can be seen because having X t being greater than i means that each random choice will result in an element that is either at least i steps before the desired element,or is after the desired element.There are n?i such elements,out of the total n elements that we were pricking from.So,for a single one of the choices to be from such a range, we have a probability of(n?i)/n=(1?i/n).Since each of the selections was independent,the total probability that all of them were is(1?i/n)t, as /doc/8010751696.html,stly,we can note that since the linked list has length n,the probability that X t is greater than n is equal to zero.d.Since we have that t>0,we know that the function f(x)=x t is increasing,so,that means that x t≤f(x).So,n?1r=0r t=nr t dr≤nf(r)dr=e.E[X t]≤nr=1 (1?r/n)t= nr=1ti=0ti(?r/n)i= ti=0nr=1ti(?r/n)i =ti=0ti(?1)in i?1+ n?1r=0 (r)tti=0ti(?1)in i?1+n i+1/n ≤ti=0ti(?1)in ii+1=1t+1ti=0t+1i+1(?n)i≤(1?n)t+1t+1f.We just put together parts b and e to get that it runs in time O(t+n/(t+1)).But,this is the same as O(t+n/t).13g.Since we have that for any number of iterations t that the ?rst algorithm takes to ?nd its answer,the second algorithm will return it in time O (t +n/t ).In particular,if we just have that t =√n .The second algorithm takestime only O (√n ).This means that tihe ?rst list search algorithm is O (√n )as well.h.If we don’t have distinct key values,then,we may randomly select an element that is further along than we had been before,but not jump to it because it has the same key as what we were currently at.The analysis will break when we try to bound the probability that X t ≥i .14。
算法导论第三版答案
Procedure BINARY-SEARCH takes a sorted array A, a value , and a range Œlow : : high of the array, in which we search for the value . The procedure compares to the array entry at the midpoint of the range and decides to eliminate half the range from further consideration. We give both iterative and recursive versions, each of which returns either an index i such that AŒi D , or NIL if no utions for Chapter 2: Getting Started
AŒlow : : high contains the value . The initial call to either version should have the parameters A; ; 1; n.
Selected Solutions for Chapter 2: Getting Started
2-3
d. We follow the hint and modify merge sort to count the number of inversions in ‚.n lg n/ time.
To start, let us define a merge-inversion as a situation within the execution of merge sort in which the MERGE procedure, after copying AŒp : : q to L and AŒq C 1 : : r to R, has values x in L and y in R such that x > y. Consider an inversion .i; j /, and let x D AŒi and y D AŒj , so that i < j and x > y. We claim that if we were to run merge sort, there would be exactly one mergeinversion involving x and y. To see why, observe that the only way in which array elements change their positions is within the MERGE procedure. Moreover, since MERGE keeps elements within L in the same relative order to each other, and correspondingly for R, the only way in which two elements can change their ordering relative to each other is for the greater one to appear in L and the lesser one to appear in R. Thus, there is at least one merge-inversion involving x and y. To see that there is exactly one such merge-inversion, observe that after any call of MERGE that involves both x and y, they are in the same sorted subarray and will therefore both appear in L or both appear in R in any given call thereafter. Thus, we have proven the claim.
算法导论中文版答案
24.2-3
24.2-4
24.3-1 见图 24-6 24.3-2
24.3-3
24.3-4 24.3-5 24.3-6
24.3-7
24.3-8 这种情况下不会破坏已经更新的点的距离。 24.4**** 24.5****
25.1-1 见图 25-1 25.1-2 为了保证递归定义式 25.2 的正确性 25.1-3
8.3-3 8.3-4
8.3-5(*) 8.4-1 见图 8-4 8.4-2
8.4-3 3/2,1/2 8.4-4(*) 8.4-5(*)
9.1-1
9.1-2 9.2-1 9.3-1
第九章
9.3-2 9.3-3
9.3-4 9.3-5
9.3-6 9.3-7
9.3-8
9.3-9
15.1-1
6.4-4
6.4-5
6.5-1 据图 6-5 6.5-2
6.5-3 6.5-4 6.5-5
6.5-6 6.5-7
6.5-8
7.1-1 见图 7-1 7.1-2
7.1-3 7.1-4 7.2-1 7.2-2
7.2-3 7.2-4 7.2-5
第七章
7.2-6 7.3-1
7.3-2
7.4-1 7.4-2
5.3-6
6.1-1 6.1-2 6.1-3 6.1-4 6.1-5 6.1-6
第6章
6.1-7
6.2-1 见图 6-2 6.2-2
6.2-3
6.2-4
6.2-5 对以 i 为根结点的子树上每个点用循环语句实现 6.2-6
6.3-1
见图 6-3 6.3-2
6.3-3
6.4-1 见图 6-4 6.4-2 HEAPSORT 仍然正确,因为每次循环的过程中还是会运行 MAX-HEAP 的过程。 6.4-3
C程序设计(第三版)习题答案(7-9章) 谭浩强著(2)_官田
{temp2=a[j];
a[j]=temp1;
temp1=temp2;
}
break;
for (j=i+1;j<N;j++)
{if(a[i]!=0 && a[j]!=0)
if (a[j]%a[i]==0)
a[j]=0; }
printf("\n");
loca=-1;
while((loca==0)&&(top<=bott))
{min=(bott+top)/2;
if(number==a[min])
{loca=min;
if(flag1)
{ printf("\na[%d][%d]=%d\n",i,maxj,max);
flag2=1;
}
}
if(!flag2) printf("NOT");
printf("\n");
}
}
7.7
main()
{int a[16][16],i,j,k,p,m,n;
p=1;
while(p==1)
{scanf("%d",&n);
}
}
7.8
#define N 10
#define M 10
main()
{int i,j,k,m,n,flag1,flag2,a[N][M],max,maxi,maxj;
scanf("%d,%d",&n,&m);
数据结构第三版第七章作业参考答案
else { t=(BTNode *)malloc(sizeof(BTNode));
t->data=b->data; t1=Swap(b->lchild); t2=Swap(b->rchild); t->lchild=t2; t->rchild=t1; } return t; }
}
7.7 假设二叉树采用二叉链存储结构,t 指向根结点,p 所指结点为任一给 定的结点,设 计一个算法,输出从根结点到p 所指结点之间路径。
解:本题可以采用《教程》中例 7.8 的方法(只需对该算法作简单修改即
可
)
。
这
里
介
绍另一种方法,即非递归后序遍历树t(参见《教程》7.4.3 小节后序遍历非
递
归
二叉树树 形表示。
答:由《教程》7.6 节的构造算法得到的二叉树的构造过程和二叉树如图 7.3 所示。
b 左:c 右:ed
a 左:cbed 右:hgijf
f 左:hgij 右:空
c 左:空 右:空
d
g
左:e
左:h
右:空 右:ij
e 左:空 右:空
h 左:空 右:空
i 左:空 右:j
j 左:空 右:空
图 7.3 二叉树的构造过程
7.3 设给定权集 w={2,3,4,7,8,9},试构造关于 w 的一棵哈夫曼树,并求其带权 路径长度 WPL。
答:本题的哈夫曼树如图 7.4 所示。
33
18
15
9
97
8
5
4
2
3
图 7.4 一棵哈夫曼树
其带权路径长度WPL=(9+7+8)×2+4×3+(2+3)×4=80。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Exercise 7.2-4
Let’s say that by “almost sorted” we mean that A[i] is at most c positions from its correct place in the sorted array, for some constant c. For INSERTIONSORT, we run the inner-while loop at most c times before we find where to insert A[j] for any particular iteration of the outer for loop. Thus the running time time is O(cn) = O(n), since c is fixed in advance. Now suppose we run QUICKSORT. The split of PARTITION will be at best n − c to c, which leads to O(n2) running time.
Chapter 7
Michelle Bodnar, Andrew Lohr
April 12, 2016
Exercise 7.1-1
13 19 9 5 12 8 7 4 21 2 6 11 13 19 9 5 12 8 7 4 21 2 6 11 13 19 9 5 12 8 7 4 21 2 6 11 9 19 13 5 12 8 7 4 21 2 6 11 9 5 13 19 12 8 7 4 21 2 6 11 9 5 13 19 12 8 7 4 21 2 6 11 9 5 8 19 12 13 7 4 21 2 6 11 9 5 8 7 12 13 19 4 21 2 6 11 9 5 8 7 4 13 19 12 21 2 6 11 9 5 8 7 4 13 19 12 21 2 6 11 9 5 8 7 4 2 19 12 21 13 6 11 9 5 8 7 4 2 6 12 21 13 19 11 9 5 8 7 4 2 6 11 21 13 19 12 Exercise 7.1-2
Exercise 7.1-3
The for loop makes exactly r − p iterations, each of which takes at most constant time. The part outside the for loop takes at most constant time. Since r − p is the size of the subarray, PARTITION takes at most time proportional to the size of the subarray it is called on.
sition of the array (Exercise 7.1-2) so the algorithm exhibits worst-case behavior.
Exercise 7.2-3
If the array is already sorted in decreasing order, then, the pivot element is less than all the other elements. The partition step takes Θ(n)oblem of size n − 1 and a subproblem of size 0. This gives us the recurrence considered in 7.2-1. Which we showed has a solution that is Θ(n2).
Exercise 7.1-4
To modify QUICKSORT to run in non-increasing order we need only modify line 4 of PARTITION, changing ≤ to ≥.
1
Exercise 7.2-1
By definition of Θ, we know that there exists c1, c2 so that the Θ(n) term is between c1n and c2n. We make that inductive hypothesis be that c1m2 ≤ T (m) ≤ c2m2 for all m < n, then, for large enough n,
If all elements in the array have the same value, PARTITION returns r. To make PARTITION return q = (p + r)/2 when all elements have the same value, modify line 4 of the algorithm to say this: if A[j] ≤ x and j(mod2) = (p + 1)(mod2). This causes the algorithm to treat half of the instances of the same value to count as less than, and the other half to count as greater than.
c1n2 ≤ c1(n − 1)2 + c1n ≤ T (n − 1) + Θ(n)
= T (n) = T (n − 1) + Θ(n) ≤ c2(n − 1)2 + c2n ≤ c2n2
Exercise 7.2-2
The running time of QUICKSORT on an array in which evey element has the same value is n2. This is because the partition will always occur at the last po-