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章
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
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算法导论作业
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ΩΩΩΘ。
USC算法导论作业4
USC算法导论作业4CSCI303Homework4Problem1(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:17841910652293Show 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)?1Heapify(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.The?rst two lines execute in constant time and Heapify runs in time O(lg n),so this algorithm runs in O(lg n)time.。
算法导论参考 答案
第二章算法入门由于时间问题有些问题没有写的很仔细,而且估计这里会存在不少不恰当之处。
另,思考题2-3 关于霍纳规则,有些部分没有完成,故没把解答写上去,我对其 c 问题有疑问,请有解答方法者提供个意见。
给出的代码目前也仅仅为解决问题,没有做优化,请见谅,等有时间了我再好好修改。
插入排序算法伪代码INSERTION-SORT(A)1 for j ←2 to length[A]2 do key ←A[j]3 Insert A[j] into the sorted sequence A[1..j-1]4 i ←j-15 while i > 0 and A[i] > key6 do A[i+1]←A[i]7 i ←i − 18 A[i+1]←keyC#对揑入排序算法的实现:public static void InsertionSort<T>(T[] Input) where T:IComparable<T>{T key;int i;for (int j = 1; j < Input.Length; j++){key = Input[j];i = j - 1;for (; i >= 0 && Input[i].CompareTo(key)>0;i-- )Input[i + 1] = Input[i];Input[i+1]=key;}}揑入算法的设计使用的是增量(incremental)方法:在排好子数组A[1..j-1]后,将元素A[ j]揑入,形成排好序的子数组A[1..j]这里需要注意的是由于大部分编程语言的数组都是从0开始算起,这个不伪代码认为的数组的数是第1个有所丌同,一般要注意有几个关键值要比伪代码的小1.如果按照大部分计算机编程语言的思路,修改为:INSERTION-SORT(A)1 for j ← 1 to length[A]2 do key ←A[j]3 i ←j-14 while i ≥ 0 and A[i] > key5 do A[i+1]←A[i]6 i ←i − 17 A[i+1]←key循环丌变式(Loop Invariant)是证明算法正确性的一个重要工具。
算法导论答案 (4)
算法导论答案第一章:算法概述啊算法的定义算法是一系列解决问题的明确指令。
它是一个有穷步骤集,其中每个步骤或操作由确定性和可行性特征。
算法是通过将预期的输入转换为输出来解决问题的工具。
第二章:插入排序插入排序的思想插入排序是一种简单直观的排序算法,其基本思想是将待排序的序列分为已排序和未排序两部分,每次从未排序的部分中取出一个元素,并将其插入到已排序部分的正确位置,直到所有元素都被排序。
插入排序的算法实现以下是插入排序的伪代码:INSERTION-SORT(A)for j = 2 to A.lengthkey = A[j]// Insert A[j] into the sorted sequence A[1.. j-1].i = j - 1while i > 0 and A[i] > keyA[i + 1] = A[i]i = i - 1A[i + 1] = key插入排序的时间复杂度插入排序的时间复杂度为O(n^2),其中n是排序的元素个数。
虽然插入排序的最坏情况下的复杂度很高,但是对于小规模的数据集,插入排序是一种较快的排序算法。
第三章:分治策略分治策略的基本思想分治策略是一种解决问题的思想,它将问题的规模不断缩小,直到问题足够小而可以直接解决。
然后将子问题的解合并起来,得到原问题的解。
分治策略的应用实例一种经典的应用分治策略的算法是归并排序。
归并排序将待排序的序列划分为两个子序列,分别排序后再将两个有序子序列合并为一个有序序列。
以下是归并排序的伪代码:MERGE-SORT(A, p, r)if p < rq = floor((p + r) / 2)MERGE-SORT(A, p, q)MERGE-SORT(A, q + 1, r)MERGE(A, p, q, r)MERGE(A, p, q, r)n1 = q - p + 1n2 = r - qlet L[1..n1+1] and R[1..n2+1] be new arraysfor i = 1 to n1L[i] = A[p + i - 1]for j = 1 to n2R[j] = A[q + j]L[n1 + 1] = infinityR[n2 + 1] = infinityi = 1j = 1for k = p to rif L[i] <= R[j]A[k] = L[i]i = i + 1elseA[k] = R[j]j = j + 1分治策略的时间复杂度归并排序的时间复杂度为O(nlogn),其中n是待排序序列的长度。
算法导论参考答案
第二章算法入门由于时间问题有些问题没有写的很仔细,而且估计这里会存在不少不恰当之处。
另,思考题2-3 关于霍纳规则,有些部分没有完成,故没把解答写上去,我对其 c 问题有疑问,请有解答方法者提供个意见。
给出的代码目前也仅仅为解决问题,没有做优化,请见谅,等有时间了我再好好修改。
插入排序算法伪代码INSERTION-SORT(A)1 for j ←2 to length[A]2 do key ←A[j]3 Insert A[j] into the sorted sequence A[1..j-1]4 i ←j-15 while i > 0 and A[i] > key6 do A[i+1]←A[i]7 i ←i − 18 A[i+1]←keyC#对揑入排序算法的实现:public static void InsertionSort<T>(T[] Input) where T:IComparable<T>{T key;int i;for (int j = 1; j < Input.Length; j++){key = Input[j];i = j - 1;for (; i >= 0 && Input[i].CompareTo(key)>0;i-- )Input[i + 1] = Input[i];Input[i+1]=key;}}揑入算法的设计使用的是增量(incremental)方法:在排好子数组A[1..j-1]后,将元素A[ j]揑入,形成排好序的子数组A[1..j]这里需要注意的是由于大部分编程语言的数组都是从0开始算起,这个不伪代码认为的数组的数是第1个有所丌同,一般要注意有几个关键值要比伪代码的小1.如果按照大部分计算机编程语言的思路,修改为:INSERTION-SORT(A)1 for j ← 1 to length[A]2 do key ←A[j]3 i ←j-14 while i ≥ 0 and A[i] > key5 do A[i+1]←A[i]6 i ←i − 17 A[i+1]←key循环丌变式(Loop Invariant)是证明算法正确性的一个重要工具。
算法导论-sch4 Randomized Algorithms
5 3 1 2 1,
算法设计与分析
4, 5 3 1 2 1,
4, 5
1 2, 1, 2 3
13
Min Cut(3)
出错概率
2 n ( n 1) 1 e 重复k次出错概率为 n(n 1)
k
2k
本算法是一个Monte Carlo型算法
2012/10/31 算法设计与分析 16
运行时间的期望和方差
第4章(补充) 随机算法
4.1 概述 4.2 时间复杂性度量 4.3 一般设计风范 4.4 4 4 随机取样 4.5 串匹配算法 4.6 格点逼近问题
4.3 一般设计风范(1)
1.挫败对手(Foiling the Adversary) 将不同的算法组成算法群, 根据输入实例的不同随机地或 有选择地选取不同的算法, 以使性能达到最佳. 2.随机采样(Random Sampling) 用“小”样本群的信息, 指导整体的求解. 3.随机搜索(Random Search) 是一种简单易行的方法, 可以从统计角度分析算法的平均 性能, 如果将搜索限制在有解或有较多解的区域, 可以大 大提到搜索的成功概率. 4.指纹技术(Fingerprinting) 利用指纹信息可以大大减少对象识别的工作量 利用指纹信息可以大大减少对象识别的 作量. 通过随机 映射的取指方法, Karp和Rabin得到了一个快速的串匹配 随机算法.
确定的 算法 非确定的
2012/10/31
算法设计与分析
7
研究意义(3)
有效的随机算法:
素性测试问题: 提出的第一个多项式时间的算 法是随机算法; 法是随机算法 匹配问题: 存在NC类的随机并行算法,而没有 NC类的确定并行算法; 无向图可达问题 题: 存在logspace g p 的随机算法, 算 而没有logspace的确定算法,
算法导论习题答案 (4)
The father now has to decide how to procure skis for his daughter for every weekly session (until she quits). One can buy skis at a one-time cost of B dollars, or rent skis at a weekly cost of R dollars. (Note that one can buy skis at any time—e.g., rent for two weeks, then buy.)
(a) Suppose that (starting from an empty queue) we do 3 insertions, then 2 removals,
then 3 more insertions, and then 2 more removals. What is the total cost of these 10
Problem Set 4 Solutions
Reading: Chapters 17, 21.1–21.3 Both exercises and problems should be solved, but only the problems should be turned in.
算法导论习题
//在合并排序中对小数组采用插入排序#include<stdio.h>void main(){void MERGE_SORT(int a[],int p,int r,int k);int a[12]; //={3,0,1,10,9,5,4,12,7,8,2,6};int k=3,n=12;int i,j,s;int tmp=0;printf("请输入12个正整数:\n");for(i=0;i<12;i++)scanf("%d",&a[i]);for(i=0;i<=3;i++){for(j=i*3+1;j<i*3+3;j++){s=j;while(s>=i*3+1){if(a[s]<a[s-1])tmp=a[s],a[s]=a[s-1],a[s-1]=tmp;s--;}}}printf("第一步对4个长度3的子列表进行插入排序的结果为:\n");for(i=0;i<12;i++)printf("%d,",a[i]);printf("\n");MERGE_SORT(a,0,3,3);printf("第二步对4个子列表进行合并排序的结果为:\n");for(i=0;i<12;i++)printf("%d,",a[i]);printf("\n");} void MERGE_SORT(int a[],int p,int r,int k) {void MERGE(int a[],int p,int q,int r,int k);int q;if(p<r){q=(p+r)/2;MERGE_SORT(a,p,q,k);MERGE_SORT(a,q+1,r,k);MERGE(a,p,q,r,k);}}void MERGE(int a[],int p,int q,int r,int k) {int n1=(q-p+1)*k,n2=(r-q)*k;int i,j,s;int *L=new int[n1];int *R=new int[n2];for(i=0;i<n1;i++)L[i]=a[p*k+i];for(j=0;j<n2;j++)R[j]=a[(q+1)*k+j];i=0;j=0;for(s=p*3;s<=(r+1)*3-1;s++){if(i>n1-1)a[s]=R[j++];else if(j>n2-1)a[s]=L[i++];else if(L[i]<R[j])a[s]=L[i++];elsea[s]=R[j++];}}//用分治法在数组中查找逆序对#include<stdio.h>void main(){int count_inversion(int a[],int p,int r);int a[5]={5,4,3,2,1};printf("数组的逆序对是%d个\n",count_inversion(a,0,4));}int merge_inversion(int a[],int p,int q,int r){int n1=q-p+1;int n2=r-q;int *L=new int[n1];int *R=new int[n2];int i,j,k,v;for(i=0;i<n1;++i)L[i]=a[p+i];for(j=0;j<n2;++j)R[j]=a[q+1+j];i=0;j=0;v=0;for(k=p;k<=r;++k){if(i>n1-1)a[k]=R[j++];else if(j>n2-1)a[k]=L[i++];else if(L[i]>R[j]){a[k]=R[j++];v+=n1-i;}elsea[k]=L[i++];}delete L;delete R;return v;}int count_inversion(int a[],int p,int r){int v=0,q;if(p<r){q=(p+r)/2;v+=count_inversion(a,p,q);v+=count_inversion(a,q+1,r);v+=merge_inversion(a,p,q,r);}return v;}//用插入方法建堆#include"stdio.h"void HEAP_INCREASE_KEY(int a[],int i,int key) {int tmp;if(key>a[i-1])a[i-1]=key;while(i>1&&a[i/2-1]<a[i-1]){tmp=a[i/2-1],a[i/2-1]=a[i-1],a[i-1]=tmp;i=i/2;}}void MAX_HEAP_INSERT(int a[],int key,int heap_size){heap_size+=1;a[heap_size-1]=0;HEAP_INCREASE_KEY(a,heap_size,key); }void BUILD_MAX_HEAP(int a[],int lengh){int heap_size=1;int i;for(i=2;i<=lengh;i++){MAX_HEAP_INSERT(a,a[i-1],heap_size);heap_size++; //堆的长度要随着循环的次数增长}}void main(){int j;int a[10]={15,84,62,16,29,35,6,18,9,17};BUILD_MAX_HEAP(a,10);for(j=0;j<10;j++)printf("%d\n",a[j]);}#include"stdio.h"void MAX_D_HEAPIFY(int a[],int i,int d,int heap_size){int n=d,j,largest;int tmp;int *child=new int[n];for(j=0;j<n;j++)child[j]=(i-1)*d+2+j;if(child[0]<=heap_size&&a[child[0]-1]>a[i-1])largest=child[0];elselargest=i;for(j=1;j<n;j++){if(child[j]<=heap_size&&a[child[j]-1]>a[largest-1])largest=child[j];}if(largest!=i){tmp=a[largest-1],a[largest-1]=a[i-1],a[i-1]=tmp;MAX_D_HEAPIFY(a,largest,d,heap_size);}}void BUILD_MAX_D_HEAP(int a[],int d,int heap_size){int i,j;j=heap_size%d;if(j==0||j==1)i=heap_size/d;elsei=heap_size/d+1;//由叶子节点求父节点有两种情况for(i;i>=1;i--)MAX_D_HEAPIFY(a,i,d,heap_size);}int EXTRACT_MAX(int a[],int d,int heap_size) {int tmp;tmp=a[heap_size-1];a[heap_size-1]=a[0];a[0]= tmp;heap_size--;MAX_D_HEAPIFY(a,1,d,heap_size);return a[heap_size];}void main(){inta[20]={52,47,16,58,23,26,14,18,59,68,47,19,35,29, 61,82,74,75,98,81};// int b[18]={25,11,15,9,8,17,21,40,18,11,10,20,14,15,19, 21,7,10};int d=5,j,largest;BUILD_MAX_D_HEAP(a,5,20);// BUILD_MAX_D_HEAP(b,5,18);for(j=0;j<20;j++)printf("%d\n",a[j]);largest=EXTRACT_MAX(a,5,20);for(j=0;j<20;j++)printf("%d\n",a[j]);printf("%d\n",largest);/* for(j=0;j<18;j++)printf("%d\n",b[j]);*/#include"stdio.h"void MAX_D_HEAPIFY(int a[],int i,int d,int heap_size){int n=d,j,largest;int tmp;int *child=new int[n];for(j=0;j<n;j++)child[j]=(i-1)*d+2+j;if(child[0]<=heap_size&&a[child[0]-1]>a[i-1])largest=child[0];elselargest=i;for(j=1;j<n;j++){if(child[j]<=heap_size&&a[child[j]-1]>a[largest-1])largest=child[j];}if(largest!=i){tmp=a[largest-1],a[largest-1]=a[i-1],a[i-1]=tmp;MAX_D_HEAPIFY(a,largest,d,heap_size);}}void BUILD_MAX_D_HEAP(int a[],int d,int heap_size){int i,j;j=heap_size/d;if(j==0||j==1)i=heap_size/d;elsei=heap_size/d+1;//由叶子节点求父节点有两种情况for(i;i>=1;i--)MAX_D_HEAPIFY(a,i,d,heap_size);}void HEAP_INCREASE_KEY(int a[],int i,int d,int key){int tmp,j;if(a[i-1]<=key)a[i-1]=key;while(i>1){if(i%d==0||i%d==1)j=i/d;elsej=i/d+1;if(a[j-1]<a[i-1]){tmp=a[j-1],a[j-1]=a[i-1],a[i-1]=tmp;i=j;}else break;}}void INSERT(int a[],int key,int d,int heap_size) {heap_size+=1;a[heap_size-1]=0;HEAP_INCREASE_KEY(a,heap_size,d,key); }void main(){inta[20]={52,47,16,58,23,26,14,18,59,68,47,19,35,29, 61,82,74,75,98,81};int j,s=0;BUILD_MAX_D_HEAP(a,5,19);for(j=0;j<20;j++){printf("%d,",a[j]);s+=1;if(s%6==0)printf("\n");}INSERT(a,a[19],5,19);s=0;printf("\n");for(j=0;j<20;j++){printf("%d,",a[j]);s+=1;if(s%6==0)printf("\n");}}#include"stdio.h"void MAX_D_HEAPIFY(int a[],int i,int d,int heap_size){int n=d,j,largest;int tmp;int *child=new int[n];for(j=0;j<n;j++)child[j]=(i-1)*d+2+j;if(child[0]<=heap_size&&a[child[0]-1]>a[i-1])largest=child[0];elselargest=i;for(j=1;j<n;j++){if(child[j]<=heap_size&&a[child[j]-1]>a[largest-1])largest=child[j];}if(largest!=i){tmp=a[largest-1],a[largest-1]=a[i-1],a[i-1]=tmp;MAX_D_HEAPIFY(a,largest,d,heap_size);}}void BUILD_MAX_D_HEAP(int a[],int d,int heap_size){int i,j;j=heap_size/d;if(j==0||j==1)i=heap_size/d;elsei=heap_size/d+1;//由叶子节点求父节点有两种情况for(i;i>=1;i--)MAX_D_HEAPIFY(a,i,d,heap_size);}void HEAP_DECREASE_KEY(int a[],int i,int d,int key,int heap_size){if(a[i-1]>=key)a[i-1]=key;MAX_D_HEAPIFY(a,i,d,heap_size);}void main(){inta[20]={52,47,16,58,23,26,14,18,59,68,47,19,35,29, 61,82,74,75,98,81};int key=1,s=0,j;BUILD_MAX_D_HEAP(a,5,20);for(j=0;j<20;j++){printf("%d,",a[j]);s+=1;if(s%6==0)printf("\n");}printf("\n");s=0;HEAP_DECREASE_KEY(a,3,5,key,20);for(j=0;j<20;j++){printf("%d,",a[j]);s+=1;if(s%6==0)printf("\n");}}#include"stdio.h"void main(){//int a[10]={6,4,12,7,9,11,5,13,18,8};int a[10]={20,18,17,14,16,10,8,9,8,15};int i=9,j;int heap_size;void BULD_MAX_HEAP(int a[]);int HEAP_DELETE(int a[],int i);BULD_MAX_HEAP(a);heap_size=HEAP_DELETE(a,i);printf("删除第i个元素后的堆是:\n");for(j=0;j<heap_size;j++)printf("%d\n",a[j]);}void BULD_MAX_HEAP(int a[]){void MAX_HEAPIFY(int a[],int j,int heap_size);int heap_size=10;int j;for(j=4;j>=0;j--)MAX_HEAPIFY(a,j,heap_size);printf("堆a是:\n");for(j=0;j<heap_size;j++)printf("%4d",a[j]);printf("\n");}void MAX_HEAPIFY(int a[],int j,int heap_size) {int left=2*(j+1);int right=2*(j+1)+1;//结点与数组下标之间要转换int largest=0,temp;if(left<=heap_size&&a[left-1]>a[j])largest=left-1;elselargest=j;if(right<=heap_size&&a[right-1]>a[largest])largest=right-1;if(largest!=j){temp=a[largest];a[largest]=a[j];a[j]=temp;MAX_HEAPIFY(a,largest,heap_size);}}int HEAP_DELETE(int a[],int i){int temp,key=a[9],key1=a[i-1];int heap_size=10;temp=a[9];a[9]=a[i-1];a[i-1]=temp;heap_size--;if(key>key1){while(i>1&&a[i/2-1]<a[i-1])//如果a[9]大于i结点的值,则通过不断与父结点的比较//来确它的位置{temp=a[i/2-1],a[i/2-1]=a[i-1],a[i-1]=temp;i=i/2;}}elseMAX_HEAPIFY(a,i-1,heap_size);//如果a[9]比i结点的值要小,则从i结点开始堆维护return heap_size;}//建立最小堆#include"stdio.h"void MIN_HEAPIFY(int a[],int i,int heap_size){int small,tmp;int left=2*i,right=2*i+1;if(left<=heap_size&&a[left-1]>a[i-1])small=left;elsesmall=i;if(right<=heap_size&&a[right-1]>a[small-1]) small=right;if(small!=i){tmp=a[small-1],a[small-1]=a[i-1],a[i-1]=tmp;MIN_HEAPIFY(a,small,heap_size);}}void BUILD_MIN_HEAP(int a[],int heap_size) {int i;for(i=(heap_size/2);i>=1;i--)MIN_HEAPIFY(a,i,heap_size);}void HEAPSORT(int a[],int lengh){int i,tmp;int heap_size=lengh;BUILD_MIN_HEAP(a,heap_size);for(i=lengh;i>=2;i--){tmp=a[i-1],a[i-1]=a[0],a[0]=tmp;heap_size--;MIN_HEAPIFY(a,1,heap_size);}}void main(){int a[10]={23,6,21,3,7,5,8,54,14,10};int i;HEAPSORT(a,10);for(i=0;i<10;i++)printf("%d\n",a[i]);}//PARTITION的最初版本#include"stdio.h" int HOARE_PARTITION(int a[],int p,int r){int x,tmp;int i,j;x=a[p-1];i=p-1;j=r+1;while(1){while(a[--j-1]>x);while(a[++i-1]<x);if(i<j)tmp=a[i-1],a[i-1]=a[j-1],a[j-1]=tmp;elsereturn j;}}void QUICK_SORT(int a[],int p,int r){int q;if(p<r){q=HOARE_PARTITION(a,p,r);QUICK_SORT(a,p,q);QUICK_SORT(a,q+1,r);}}void main(){int i;inta[20]={10,58,46,23,26,48,47,59,68,23,12,19,17,24, 43,81,76,72,98,46};QUICK_SORT(a,1,20);for(i=0;i<20;i++)printf("%d\n",a[i]);/*对插入排序来说,当其输入已“几乎”排好序时,运行时间是很快的。
算法导论答案(经典)
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
16.3-1 16.3-2Leabharlann 16.3-3 16.3-4
16.3-5
16.3-6 那就推广到树的结点有三个孩子结点,证明过程同引理 16.3 的证明。 16.3-7 16.3-8
第 24 章
24.1-1 同源顶点 s 的运行过程,见图 24-4 24.1-2
24.1-3
24.1-4 24.1-5* 24.1-6 修改 Bellman-Ford 算法,先找到负环上的一个节点,再依次找到负环上的一个节点,再依 次找到负环上的其他节点。 24.2-1 见图 24-5 24.2-2 最后一次不影响结果
len=j;//更新 len
} cout<<len<<endl; } return 0; } 15.5-1
15.5-2 15.5-3
15.5-4
16.1-1
第 16 章
16.1-2 16.1-3
16.1-4 16.2-1 16.2-2
16.2-3
16.2-4
16.2-5 16.2-6
16.2-7
第 25 章
25.1-4 25.1-5
25.1-6 25.1-7 25.1-8
25.1-9 25.1-10 25.2-1 见图 25-4 25.2-2 25.2-3 25.2-4
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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.。