USC算法导论作业4

合集下载

算法导论文档

算法导论文档

第一课课程细节;绪论:算法分析,插入排序法(Insertion Sort),归并排序(Merge Sort) 阅读:1-2章发测验02 演示课1 算法的正确性发《作业1》3 第二课渐进记号(Asymptotic Notation)。

递归公式(Recurrences):置换法,迭代法,主方法阅读:3-4 章,除了§4.44 第三课分治法:Strassen 算法,费氏数列,多项式乘法。

阅读:28 章第2 节,30章第1节5 演示课2 递归公式,松散性阅读:Akra-Bazzi 的讲义6 第四课快速排序法,随机化算法阅读:5 章1 到 3 节,7 章收《作业1》发《作业2》7 演示课3 排序法:堆排序,动态集合,优先队列阅读:6 章8 第五课线性时间的排序法:时间下界,计数排序法,基数排序法阅读:8 章第1 到3 节收《作业2》发《作业3》9 第六课顺序统计学,中位数阅读:9 章10 演示课4 中位数的应用,桶排序阅读:8 章第 4 节11 第七课散列,全域散列阅读:11 章1 到3 节收《作业3》发《作业4》12 第八课散列函数,完美散列阅读:11 章第5 节13 演示课5 测验1 复习收《作业4》14 评分后的作业4可以在中午拿到15 测验116 演示课6 二叉搜索树,树的遍历阅读:12 章1 到 3 节17 第九课二叉搜索树和快速排序法之间的关系;随机二叉搜索树的分析阅读:12 章4 节发《作业5》18 第十课红黑树,旋转,插入,删除阅读:13 章19 演示课7 2-3树,B-树阅读:18 章1 到 2 节20 第十一课高级数据结构,动态顺序统计,线段树(区间树)阅读:14 章收《作业5》发《作业6》21 第十二课计算几何,区间查询阅读:33 章1 到 2 节22 演示课8 凸多边形阅读:33 章3 节23 第十三课van Emde Boas树,优先队列阅读:van Emde Boas 的讲义收《作业6》发《作业7》24 第十四课平摊分析,表的复制,可能法阅读:17 章25 演示课9 竞争分析,自我排序列26 第十五课动态规划,最长公共子序列,最优二叉搜索树阅读:15 章收《作业7》发《作业8》27 第十六课贪婪算法,最小生成树阅读:16 章1 到 3 节,23 章28 演示课10 贪婪算法和动态规划的范例29 第十七课最短路径1,Dijkstra算法,广度优先搜索阅读:22 章1, 2 节;第580 - 587 页,24章 3 节收《作业8》发《作业9》30 演示课11 深度优先搜索,拓扑排序阅读:22 章3 到 5 节31 第十八课最短路径2,Bellman-Ford算法,DAG最短路径,差分约束阅读:24 章1, 2, 4, 5 节32 第十九课所有点对最短路径,Floyd-Warshall,Johnson 的算法阅读:25 章收《作业9》33 第二十课不相交集合的数据结构阅读:21 章34 评分后的作业9可以在中午拿到35 第二十一课带回家发下测验2 ; 道德,解决问题(强制参加)发测验236 没有演示课- 解答测验2!37 没有课算法程序比赛开始(非强制参加)收测验238 第二十二课网络流,最大流最小割切定理阅读:26 章1 - 2 节发《作业10》(选答)39 演示课12 图的匹配算法(注:最大二分匹配)阅读:26 章3 节40 第二十三课网络流,Edmonds-Karp 算法参赛答案截止41 第二十四课随堂测验;比赛颁奖;后续课程的讨论《作业10》解答。

算法导论第4章

算法导论第4章
贪心算法和动态规划算法都要求问题具有最优子 结构性质,这是2 结构性质,这是2类算法的一个共同点。但是,对于具 有最优子结构的问题应该选用贪心算法还是动态规划 最优子结构的问题应该选用贪心算法还是动态规划 算法求解? 算法求解?是否能用动态规划算法求解的问题也能用贪 心算法求解?下面研究2个经典的组合优化问题 心算法求解?下面研究2个经典的组合优化问题,并以 组合优化问题,并以 此说明贪心算法与动态规划算法的主要差别。
12
4.2 贪心算法的基本要素
2、最优子结构性质
当一个问题的最优解包含其子问题的最优解时, 称此问题具有最优子结构性质 称此问题具有最优子结构性质。问题的最优子结构性 最优子结构性质。问题的最优子结构性 质是该问题可用动态规划算法或贪心算法求解的关键 特征。
13
4.2 贪心算法的基本要素
3、贪心算法与动态规划算法的差异
2
顾名思义,贪心算法总是作出在当前看来最好的选择。 也就是说贪心算法并不从整体最优考虑,它所作出的选择 局部最优选择。当然,希望贪心算法 只是在某种意义上的局部最优 只是在某种意义上的局部最优选择。当然,希望贪心算法 得到的最终结果也是整体最优的。虽然贪心算法不能对所 有问题都得到整体最优解,但对许多问题它能产生整体最 优解。如单源最短路经问题,最小生成树问题等。在一些 情况下,即使贪心算法不能得到整体最优解,其最终结果 却是最优解的很好近似。
16
4.2 贪心算法的基本要素
用贪心算法解背包问题的基本步骤:
首先计算每种物品单位重量的价值Vi/Wi,然后,依贪心 首先计算每种物品单位重量的价值Vi/Wi,然后,依贪心 选择策略,将尽可能多的单位重量价值最高 选择策略,将尽可能多的单位重量价值最高的物品装入背包。 单位重量价值最高的物品装入背包。 若将这种物品全部装入背包后,背包内的物品总重量未超过 C,则选择单位重量价值次高的物品并尽可能多地装入背包。 依此策略一直地进行下去,直到背包装满为止。 具体算法可描述如下页:

算法导论课程作业答案

算法导论课程作业答案

算法导论课程作业答案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。

算法导论 第四章 递归

算法导论 第四章 递归

Idea of master theorem
• Recursion tree
#leaves = ah = alogbn = nlogba
a
Three common cases
• Compare f(n) with nlogba : -- 1. f(n) = O(nlogba-ε) for some constantε> 0 >> f(n) grows polynomially slower than nlogba (by an nε factor)多项式小于 -- Solution: T(n) = Θ(nlogba)
Idea of master theorem
• Recursion tree
CASE 1: The weight increases geometrically from the root to the leaves. The leaves hold a constant fraction of the total weight.
-- Consider T(n) = 2T(
n
) + lgn,
-- Rename m = lgn and we have T(2m) = 2T(2m/2) + m.
-- Set S(m) = T(2m) and we have S(m) = 2S(m/2) + m S(m) = O(mlgm) -- Changing back from S(m) to T(n), we have T(n) = T(2m) = S(m) = O(mlgm) = O(lgnlglgn)
Substitution method替换法
• The most general method: -- Guess the form of the solution猜测解的形式 -- Verify by induction数学归纳法证明 -- Solve for constants解出常数c,n0

中科大算法导论第一,二次和第四次作业答案

中科大算法导论第一,二次和第四次作业答案
第一次作业
2.2-3 再次考虑线性查找问题 (见练习2.1-3)。在平均情况 下,需要检查输入序列中的多 少个元素?假定待查找的元素 是数组中任何一个元素的可能 性是相等的。在最坏情况下有 怎样呢?用Θ形式表示的话,线 性查找的平均情况和最坏情况 运行时间怎样?对你的答案加 以说明。 • 线性查找问题 • 输入:一列数A=<a1,a2,…,an>和一 个值v。 • 输出:下标i,使得v=A[i],或者当 v不在A中出现时为NIL。 • 平均情况下需要查找 (1+2+…+n)/n=(n+1)/2 • 最坏情况下即最后一个元素为待 查找元素,需要查找n个。 • 故平均情况和最坏情况的运行时 间都为Θ(n)。
• 2.3-2改写MERGE过程,使之不使 用哨兵元素,而是在一旦数组L或R 中的所有元素都被复制回数组A后, 就立即停止,再将另一个数组中 余下的元素复制回数组A中。 • MERGE(A,p,q,r) 1. n1←q-p+1 2. n2 ←r-q 3. create arrays L[1..n1] and R[1..n2] 4. for i ←1 to n1 5. do L*i+ ←A*p+i-1] 6. for j ←1 to n2 7. do R*j+ ←A*q+j+ 8. i ←1 9. j ←1
10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21.
k ←p while((i<=n1) and (j<=n2)) do if L[i]<=R[j] do A[k]=L[i] i++ else do A[k]=R[j] j++ k++ while(i<=n1) do A[k++]=L[i++] while(j<=n2) do A[k++]=R[j++]

《算法导论(第二版)》(中文版)课后答案

《算法导论(第二版)》(中文版)课后答案

17.3-1
11
《算法导论(第二版) 》参考答案
17.3-4
17.4-3 假设第 i 个操作是 TABLE_DELETE, 考虑装载因子 : i =(第 i 次循环之后的表 中的 entry 数)/(第 i 次循环后的表的大小)= numi / sizei
19.1-1. If x is not a root node, then Degree[x]=Degree[sibling[x]]+1 If x is a root node, then Degree[x]<Degree[sibling[x]] 19.1-2
13.1-5 prove:
3
《算法导论(第二版) 》参考答案 13.1-6 2k-1 22k-1 13.2-3 13.3-5
13.4-3
4
《算法导论(第二版) 》参考答案
14.1-4
14.2-2
14.2-3 不可以,性能改变 时间复杂度由 O( lgn ) -> O( nlgn )
14.3-2 Note: 注意 Overlap 的定义稍有不同,需要重新定义。 算法:只要将 P314 页第三行的 改成>就行。 14.3-3 INTERVAL-SEARCH-SUBTREE(x, i) 1 while x ≠ nil[T] and i does not overlap int[x] 2 do if left[x] ≠ nil[T] and max[left[x]] ≥ low[i] 3 then x ← left[x] 4 else x ← right[x] 5 return x INTERVAL-SEARCH-MIN(T, i) 2 y←INTERVAL-SEARCH-SUBTREE(root[T], i) 先找第一个重叠区间 3 z←y 4 while y≠ nil[T] and left[y] ≠ nil[T] 在它的左子树上查找

USC算法导论作业3

USC算法导论作业3

CSCI303Homework3Problem1(9-1):Given a set A of n numbers,we wish tofind the k largest in sorted order using a comparison-based algorithm.Find the algorithm that implements each of the following methods with the best asymptotic worst-case running time,and analyze the running time of the algorithms in terms of n and k.a.Sort the numbers,and list the k largest.b.Build a max-priority queue from the numbers,and call Extract-Max k times.e an order-statistic algorithm tofind the i th largest number,partition around that num-ber,and sort the k largest numbers.Solution1:a.Merge-Sort(A,1,n)return A[n−k...k]This algorithm takes only as long as it takes to Merge-Sort a list of n numbers,so its running time isΘ(n lg n).b.Build-Max-Heap(A)for i←1to kB[i]←Heap-Extract-Max(A)return BThis algorithmfirst calls Build-Max-Heap on A,which has worst-case asymptotic com-plexity O(n).Then it calls Heap-Extract-Max k times,each of which has worst-case asymptotic complexity O(lg n).So the worst-case asymptotic complexity for this algorithm is O(n+k lg n).c.i←Select(A,k)A[n]↔A[i]Partition(A)Merge-Sort(A,n−k,n)return A[n−k...k]This algorithmfirst calls Select,which has worst-case asymptotic complexity O(n), then calls Partition,which also has worst-case asymptotic complexity O(n),then calls Merge-Sort to sort just the last k elements,which has worst-case asymptotic complexity O(k lg k).So the worst-case asymptotic complexity for this algorithm is O(n+k lg k).Problem2(9.3-5):Suppose that you have a“black-box”worst-case linear-time median subroutine.Give a simple, linear-time algorithm that solves the selection problem for an arbitrary order statistic.Solution2:Simple-Select(A,p,r,i)if p=rreturn A[p]A[r]↔A[Index-Of-Median(A,p,r)] Partition(A,p,r)k← r−p+12if i=kreturn A[k]else if i<kreturn Simple-Select(A,1,k−1,i)elsereturn Simple-Select(A,k+1,r,i−k)Problem3(9.3-8):Let X[1,...,n]and Y[1,...,n]be two arrays,each containing n numbers already in sorted order. Give an O(lg n)-time algorithm tofind the median of all2n elements in arrays X and Y. Solution3:Two-List-Median(X,p,q,Y,s,t)mx←Index-Of-Median(X,p,q)my←Index-Of-Median(Y,s,t)X[mx]↔X[q]Y[my]↔Y[t]Partition(X,p,q)Partition(Y,s,t)if X[mx]=Y[my]return X[mx]else if X[mx]>Y[my]return Two-List-Median(X,p,mx−1,Y,my+1,t)elsereturn Two-List-Median(X,mx+1,q,Y,s,my−1)Problem4(8.1-1):What is the smallest possible depth of a leaf in a decision tree for a comparison sort?Solution4:Given an array A that contains n elements,the smallest possible depth of a leaf in a decision tree to sort A using a comparison-type sort is n−1.To verify that A is in sorted order takes n−1 comparisons,and if fewer comparisons are used then at least one element was not compared to any of the others,so that element might not be in the correct position.Problem 5(Derived from 8.1-4):You are given a sequence of n elements to sort and a number k such that k divides n .The input sequence consists of n/k subsequences,each containing k elements.The elements in a given subsequence are all smaller than the elements in the succeeding subsequence and larger than the elements in the preceding subsequence.Thus,all that is needed to sort the whole sequence of length n is to sort the k elements in each of the n/k subsequences.Show an Ω(n lg k )lower bound on the number of comparisons needed to solve this varient of the sorting problem using a comparison-type sorting algorithm.(Hint:It is not rigorous to simply combine the lower bounds for the individual subsequences.)Solution 5:We will construct a decision tree for this varient of the sorting problem and show that it has height at least n lg k .Each leaf of the decision tree corresponds to a permutation of the original sequence.How many permutations are there?Each subsequence has k !permutations,and there are n/k subsequences,so there are (k !)n/k permutations of the whole sequence.Thus the decision tree has (k !)n/k leaves.A binary tree with (k !)n/k leaves has height at least lg (k !)n/k .lg (k !)n/k =n/k lg(k !)=Θ(n/k ·k lg k )=Θ(n lg k )Therefore the lower bound on the number of comparisons needed to solve this varient of the sorting problem using a comparison-type sorting algorithm is Ω(n lg k ).。

USC算法导论作业

USC算法导论作业

CSCI 303Homework 1Problem 1(2.1-1):Using Figure 2.2as a model,illustrate the operation of Insertion-Sort on the array A = 31,41,59,26,41,58 .Solution 1:265841594131Problem 2(2.2-1):Express the function n 3/1000−100n 2−100n +3in terms of Θ-notation.Solution 2:n 3/1000−100n 2−100n +3=Θ(n 3)Problem 3(Derived from 2.2-2):Consider sorting n numbers stored in array A by first finding the smallest element of A and exchanging it with the element in A [1].Then find the second smallest element of A ,and exchange it with A [2].Continue in this manner for the first n −1elements of A .Write pseudocode for this algorithm,which is known as Selection-Sort .Give the worst-case running times of selection sort in Θ-notation.Solution 3:Selection-Sort (A )for i ←1to length [A ]do min-value ←A [i ]min-index =ifor j =i +1to length [A ]do if A [j ]≤min-valuemin-value =A [j ]min-index =jA [i ]↔A [min-index ]The worst-case running time of Selection-Sort is Θ(n 2).Using Figure2.4as a model,illustrate the operation of merge sort on the array A= 3,41,52,26,38,57,9,49 . Solution4:Sorted SequenceInitial SequenceProblem5(Derived from1.2-2):Suppose we are comparing two sorting algorithms.Suppose that for all inputs of size n,thefirst algorithm runs in8n2seconds,while the second algorithm runs in64n lg n seconds.For whichvalues of n does thefirst algorithm beat the second algorithm?Solution5:Thefirst algorithm beats the second algorithm if8n2<64n lg n.For this to happen,n<8lg n.This is true for2≤n≤43.Problem6(1.2-3):What is the smallest value of n such that an algorithm whose running time is100n2runs fasterthan an algorithm whose running time is2n?Solution6:n=15Assume that a new Intel processor can execute1015operations per second.You have two algorithms that test whether a number is prime or not.Thefirst algorithm uses100n2operations for a number with n decimal digits.The second uses2n operations for a number with n decimal ing thefirst algorithm,how many seconds would the Intel processor take to determine whether a1000 decimal digit number is prime?Using the second algorithm,how many seconds would the Intel processor take to determine whether a1000decimal digit number is prime?Solution7:Thefirst algorithm would take10−7seconds(100nanoseconds).The second algorithm would take 10286seconds.For comparison,the universe is about4.33×1017seconds old,so it would take approximately2.5×10268times the age of the universe to solve the problem using the second algorithm.Problem8(1-1Comparison of running times):For each function f(n)and time t in the following table,determine the largest size n of a prob-lem that can be solved in time t,assuming that the algorithm to solve the problem takes f(n) microseconds.1second1minute1hour1day1month1year1centurylg n√nnn lg nn2n32nn!Solution8:1second1minute1hour1day1month1year1centurylg n210626×10723.6×10928.64×101022.63×101223.16×101323.16×1015√n10123.6×10151.3×10197.46×10216.92×10249.96×10249.96×1030 n1066×1073.6×1098.64×10102.63×10123.16×10133.16×1015 n lg n6274628014171.33×1082.76×1097.29×10107.98×10116.87×1013 n210007745600002939381621643561753856175382 n3100391153244201380231600146677 2n19253136414451n!9111213151617Problem9(Derived from3.1-2):Show that for all numbers a and b,(n+a)b=Θ(n b). Solution9:(n+a)b=bk=0bkn b−k a k(The binomial formula)=n b+bn b−1k+···+bnk b−1+k b=Θ(n b)Problem10(3.1-4):Is2n+1=O(2n)?Is22n=O(2n)?Solution10:2n+1=2×2n so2n+1=O(2n)22n=2n×2n so22n=O(2n)Problem11(Not in book):In the table below,write O if f(n)=O(g(n)),Ωif f(n)=Ω(g(n)),andΘif f(n)=Θ(g(n)).g(n)↓f(n)→5n+33.14×1088n2lg4n+n32n5n3+4n2lg n+3n12n+lg8n 5n+33.14×1088n2lg4n+n32n5n3+4n2lg n+3n12n+lg8nSolution11:g(n)↓f(n)→5n+33.14×1088n2lg4n+n32n5n3+4n2lg n+3n12n+lg8n 5n+3ΘOΩΩΩΘ3.14×108ΩΘΩΩΩΩ8n2lg4n+n3O OΘΩΩO 2n O O OΘO O5n3+4n2lg n+3n O O OΩΘO 12n+lg8nΘOΩΩΩΘ。

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

CSCI303Homework4
Problem1(6.1-1):
What are the minimum and maximum numbers of elements in a heap of height h?
Solution1:
A heap is a semi-complete binary tree,so the minimum number of elements in a heap of height h is2h,and the maximum number of elements in a heap of height h is2h+1−1.
Problem2(6.1-6):
Is the sequence 23,17,14,6,13,10,1,5,7,12 a max-heap?
Solution2:
The sequence is not a max-heap,because7is a child of6,but7>6.
Problem3(6.2-1):
Using Figure6.2as a model,illustrate the operation of Max-Heapify(A,3)on the array A= 27,17,3,16,13,10,1,5,7,12,4,8,9,10 .
Solution3:
Problem4(6.2-6):
Show that the worst-case running time of Max-Heapify on a heap of size n isΩ(lg n).(Hint:For a heap with n nodes,give node values that cause Max-Heapify to be called recursively at every node on a path from the root down to a leaf.)
Solution4:
Consider a heap of n nodes where the root node has been changed to contain the smallest value of all the nodes.Now when we call Max-Heapify on the root,the value will have to be exchanged down with its child at every level,until it reaches the lowest level.This is because,after every swapping,the value will still be smaller than both its children(since it is the minimum),until it reaches the lowest level where it has no more children.In such a heap,the number of exchanges to max-heapify the root will be equal to the height of the tree,which is lg n.So the worst case running time isΩ(lg n).
Using Figure 6.3as a model,illustrate the operation of Build-Max-Heap on the array A = 5,3,17,10,84,19,6,22,9 .Solution 5:
17
84
19
106
5
229
3
Show that the worst-case running time of Heapsort isΩ(n lg n).
Solution6:
We can see that Heapsort is a comparison-type sort,and we have shown that all comparison-type sorts must beΩ(n lg n).
Problem7(6.5-7):
The operation Heap-Delete(A,i)deletes the item in node i from heap A.Give an implementation of Heap-Delete that runs in O(lg n)time for an n-element max-heap.
Solution7:
Heap-Delete(A,i)
A[i]↔A[length(A)]
length(A)←length(A)−1
Heapify(A,i)
The algorithm deletes the element at node i,and replaces it with the last element.Then the algorithm runs Heapify from the node i.Thefirst two lines execute in constant time and Heapify runs in time O(lg n),so this algorithm runs in O(lg n)time.。

相关文档
最新文档