算法导论 第三版 第二章 答案 英

合集下载

算法导论 答案 (2)

算法导论 答案 (2)

算法导论答案算法导论概述《算法导论》是一本经典的计算机科学教材,由Thomas H. Cormen、Charles E. Leiserson、Ronald L. Rivest和Clifford Stein合著。

这本书详细介绍了算法的设计、分析和实现,并涵盖了算法导论领域的许多重要概念和技术。

本文将为你提供一些关于《算法导论》中一些常见问题的答案。

1. 什么是算法?算法是一系列明确定义的步骤,用于解决特定问题或完成特定任务。

它可以是一个计算过程、一个程序或一个有限的操作序列。

算法通常用于计算和数据处理领域,是计算机科学的核心概念。

2. 为什么学习算法很重要?学习算法的重要性体现在以下几个方面:•提高问题解决能力:算法是解决问题的有效工具。

学习算法可以帮助我们思考和理解问题,并设计出相应的解决方案。

•优化计算性能:算法的设计和分析可以帮助我们提高计算的效率和性能。

合适的算法可以在短时间内处理大规模数据集和复杂计算任务。

•促进技术创新:算法是许多技术和应用的基石,包括人工智能、机器学习、数据挖掘等。

学习算法可以为我们打开更多的研究和创新机会。

3. 《算法导论》提供了哪些内容?《算法导论》这本书详细介绍了算法的基本概念和设计技巧,并提供了许多典型算法的实现和分析。

以下是该书的一些主要内容:•算法分析:对算法进行时间复杂度和空间复杂度的理论分析,帮助我们评估算法的效率和性能。

•排序和查找算法:介绍了各种排序算法(如插入排序、归并排序、快速排序)和查找算法(如二分查找、哈希表)。

•图算法:讨论了图的表示方法和图搜索算法(如深度优先搜索、广度优先搜索)以及最短路径算法(如Dijkstra算法)等。

•动态规划和贪心算法:介绍了动态规划和贪心算法的原理和应用,用于解决具有最优子结构性质的问题。

•分治算法和递归思想:讲解了分治算法的基本原理,并提供了许多使用递归思想解决问题的例子。

•NP完全问题:探讨了NP完全问题的性质和求解方法,引导了读者进入计算复杂性理论的领域。

算法导论第三版第二章第一节习题答案

算法导论第三版第二章第一节习题答案

算法导论第三版第⼆章第⼀节习题答案2.1-1:以图2-2为模型,说明INSERTION-SORT在数组A=<31,41,59,26,41,58>上的执⾏过程。

NewImage2.1-2:重写过程INSERTION-SORT,使之按⾮升序(⽽不是按⾮降序)排序。

注意,跟之前升序的写法只有⼀个地⽅不⼀样:NewImage2.1-3:考虑下⾯的查找问题:输⼊:⼀列数A=<a1,a2,…,an >和⼀个值v输出:下标i,使得v=A[i],或者当v不在A中出现时为NIL。

写出针对这个问题的现⾏查找的伪代码,它顺序地扫描整个序列以查找v。

利⽤循环不变式证明算法的正确性。

确保所给出的循环不变式满⾜三个必要的性质。

(2.1-3 Consider the searching problem:Input: A sequence of n numbers A D ha1; a2; : : : ;ani and a value _.Output: An index i such that _ D AOEi_ or the special value NIL if _ does not appear in A.Write pseudocode for linear search, which scans through the sequence, looking for _. Using a loop invariant, prove that your algorithm is correct. Make sure that your loop invariant fulfills the three necessary properties.)LINEAR-SEARCH(A,v)1 for i=1 to A.length2 if v = A[i]3 return i4 return NIL现⾏查找算法正确性的证明。

计算机英语实用教程第三版课后练习题含答案

计算机英语实用教程第三版课后练习题含答案

计算机英语实用教程第三版课后练习题含答案第一章练习题答案1. What is the difference between a CPU and a GPU?A CPU (Central Processing Unit) is a general-purpose processor that performs tasks that require complex arithmetic and logical operations. A GPU (Graphics Processing Unit), on the other hand, is a specialized processor that is designed to handle tasks that involve highly parallelizable computations, such as those required for rendering graphics.2. What is the difference between RAM and ROM?RAM (Random Access Memory) is a type of memory that stores data temporarily while the computer is running. RAM is volatile, meaning that its contents are erased when the computer is turned off. ROM (Read-Only Memory), on the other hand, is a type of memory that stores data permanently, even when the computer is turned off. ROM is non-volatile, meaning that its contents are retned even when there is no power.3. What is the difference between a bit and a byte?A bit is the smallest unit of digital information, represented by a binary digit (0 or 1). A byte, on the other hand, is a unit of digital information that consists of eight bits. Bytes are commonly used to represent characters, such as letters and numbers.4. What is the purpose of an operating system?An operating system (OS) is a software program that manages the resources of a computer, including the CPU, memory, storage, and devices such as printers and displays. The purpose of an operating system is to provide an environment in which applications can run and interact with the hardware without directly accessing the underlying hardware.5. What is the difference between a compiler and an interpreter?A compiler is a program that translates the source code of a program into executable code that can be run on a specific computer platform. The resulting executable code can be run multiple times without the need for recompilation. An interpreter, on the other hand, is a program that reads and executes source code instructions one at a time. Interpreted code is typically slower than compiled code, but does not require the extra step of compilation before it can be run.第二章练习题答案1. What is the difference between a LAN and a WAN?A LAN (Local Area Network) is a network that connects computers and other devices that are located in the same physical location, such as an office building or a home. A WAN (Wide Area Network), on the other hand, is a network that connects computers and other devices that are located in different physical locations, often separated by vast distances.2. What is a router and how does it work?A router is a device that connects two or more networks together and forwards data between them. Routers use routing tables to determine thebest path for data to take between networks, and use protocols such as TCP/IP to communicate with other devices on the network.3. What is the difference between TCP and UDP?TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are both protocols used for transmitting data over the internet. TCP is a connection-oriented protocol, which means that it establishes avirtual circuit between two endpoints over which data can be transmitted. TCP uses error correction and flow control to ensure that data arrivesat its destination correctly and in the correct order. UDP, on the other hand, is a connectionless protocol that does not establish a virtual circuit between endpoints. UDP does not provide error correction or flow control, but is often used in situations where speed and simplicity are more important than reliability.4. What is a DNS server?A DNS (Domn Name System) server is a special type of server that translates domn names into IP addresses. When a user enters a domn name into their web browser, the browser sends a request to a DNS server to find the corresponding IP address for that domn name. The DNS serverthen returns the IP address to the browser, which can then connect tothe website.5. What is a firewall and how does it work?A firewall is a security device that is used to protect a networkfrom unauthorized access. Firewalls can be implemented as hardware or software, and typically work by examining incoming and outgoing network traffic and blocking any traffic that does not meet a set of predefinedrules. Firewalls can be configured to block specific types of traffic, such as traffic from certn IP addresses or traffic that uses a certn protocol. Firewalls can also be configured to allow or deny access to specific network resources based on user or device credentials.。

大学英语第三版第二册课后翻译练习参考答案

大学英语第三版第二册课后翻译练习参考答案

新视野读写教程第三版第二册读写教程课后翻译参考答案第一单元英译中 English is known as a world language, regularly used by many nations whose English is not their first language. Like other languages, English has changed greatly. The history of the English language can be divided into three main periods: Old English, Middle English and Modern English. The English language started with the invasion of Britain by three Germanic tribes during the 5th century AD, and they contributed greatly to the formation of the English language. During the medieval and early modern periods, the influence of English spread throughout the British Isles, and from the early 17th century its influence began to be felt throughout the world. The processes of European exploration and colonization for several centuries led to significant change in English. Today, American English is particularly influential, due to the popularity of American cinema, television, music, trade and technology, including the Internet.人们普遍认为英语是一种世界语言,经常被许多不以英语为第一语言的国家使用。

算法导论课程作业答案

算法导论课程作业答案

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

《算法导论》习题答案

《算法导论》习题答案

Chapter2 Getting Start2.1 Insertion sort2.1.2 将Insertion-Sort 重写为按非递减顺序排序2.1.3 计算两个n 位的二进制数组之和2.2 Analyzing algorithms2.2.1将函数32/10001001003n n n --+用符号Θ表示2.2.2写出选择排序算法selection-sort当前n-1个元素排好序后,第n 个元素已经是最大的元素了.最好时间和最坏时间均为2()n Θ2.3 Designing algorithms2.3.3 计算递归方程的解22()2(/2)2,1k if n T n T n n if n for k =⎧=⎨+ = >⎩ (1) 当1k =时,2n =,显然有()lg T n n n =(2) 假设当k i =时公式成立,即()lg 2lg22i i i T n n n i ===⋅,则当1k i =+,即12i n +=时,111111()(2)2(2)222(1)22lg(2)lg i i i i i i i i T n T T i i n n ++++++==+=⋅+=+== ()lg T n n n ∴ =2.3.4 给出insertion sort 的递归版本的递归式(1)1()(1)()1if n T n T n n if n Θ =⎧=⎨-+Θ >⎩2.3-6 使用二分查找来替代insertion-sort 中while 循环内的线性扫描,是否可以将算法的时间提高到(lg )n n Θ?虽然用二分查找法可以将查找正确位置的时间复杂度降下来,但是移位操作的复杂度并没有减少,所以最坏情况下该算法的时间复杂度依然是2()n Θ2.3-7 给出一个算法,使得其能在(lg )n n Θ的时间内找出在一个n 元素的整数数组内,是否存在两个元素之和为x首先利用快速排序将数组排序,时间(lg )n n Θ,然后再进行查找: Search(A,n,x)QuickSort(A,n);i←1; j←n;while A[i]+A[j]≠x and i<jif A[i]+A[j]<xi←i+1elsej←j -1if A[i]+A[j]=xreturn trueelsereturn false时间复杂度为)(n Θ。

算法导论(第二版)习题答案(英文版)

算法导论(第二版)习题答案(英文版)

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

算法导论参考答案

算法导论参考答案

第二章算法入门由于时间问题有些问题没有写的很仔细,而且估计这里会存在不少不恰当之处。

另,思考题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)是证明算法正确性的一个重要工具。

算法导论作业2答案

算法导论作业2答案

Introduction to Algorithm s Day 10 Massachusetts Institute of Technology 6.046J/18.410J Singapore-MIT Alliance SMA5503 Professors Erik Demaine,Lee Wee Sun,and Charles E.Leiserson Handout12Exercise2-1.Do Exercise5.3-1on page104of CLRS.Solution:R ANDOMIZE-I N-P LACEExchangefor todo ExchangeFor our base case,we have initialized to2.Therefore we must show that for each possible1-permutation,the subarray A[1]contains this1-permutation with probability. Clearly this is the case,as each element has a chance of of being in thefirst position.Exercise2-2.Do Exercise6.1-2on page129of CLRS.Solution:By definition,a element heap has a height of.Therefore where is and our base case is correct.Now we use induction,and assume that all trees with nodes or fewer has a height of. Next we consider a tree with nodes.Looking at the node,we know its height is one greater than its parent(and since we’re not in the base case,all nodes have a parent).The parent of the th node in the tree is also the th node in the tree.Therefore its height is.Then the th node in the tree has a height of. Therefore by induction we have shown that the height of an node tree is.Exercise2-3.Do Exercise6.4-3on page136of CLRS.Solution:The running time of H EAPSORT on an array of length that is already sorted in increasing order is because even though it is already sorted,it will be transformed back into a heap and sorted.The running time of H EAPSORT on an array of length that is sorted in decreasing order will be.This occurs because even though the heap will be built in linear time,every time the element is removed and the H EAPIFY is called it will cover the full height of the tree. Exercise2-4.Do Exercise7.2-2on page153of CLRS.Solution:The running time will be because every time partition is called,all of the elements will be put into the subarray of elements smaller than the partition.The recurrence will bewhich is clearlyExercise2-5.Do Problem7-3on page161of CLRS.Solution:(a)This sort is intuitively correct because the largest rd of the elements will eventually be sorted amung their peers.If they are in thefirst third of the array to begin with,they will be sorted into the middle third.If they are in the middle or last third,then they will obviously be sorted into their proper position.Similarly any element which belongs in the each of the thirds will be sorted into position by the three sub-sorts.(b)Which solves to(c)S TOOGE S ORT is slower than all of the other algorithms we have studied.I NSERTION, M ERGE S ORT,H EAPSORT,and Q UICKSORT.Therefore all other sorts are faster and these professors do not deserve tenure for this work!Problem2-1.Average-case performance of quicksortWe have shown that the expected time of randomized quicksort is,but we have not yet analyzed the average-case performance of ordinary quicksort.We shall prove that,under the assumption that all input permutations are equally likely,not only is the running time of ordinary quicksort,but it performs essentially the same comparisons and exchanges between input elements as randomized quicksort.Consider the implementation of P ARTITION given in lecture on a subarray:P ARTITION123for to4do if5then6exchange7exchange8returnLet be a set of distinct elements which are provided in random order(all orders equally likely) as the input array to P ARTITION,where is the size of the array.Let denote the initial value of.(a)Argue that is a random permutation of,that is,that all permuta-tions of the input subarray are equally likely.Solution:Given that is random(all orders are equally likely),there are possiblepermutations of the elements.Each element has a probabilityof being chosen as the pivot,therefore the number of permutations of the remainingelements is.Consequently the permutations are equallylikely.Define as follows:ififif(b)Consider two input arrays and consisting of the elements of suchthat for all.Suppose that we run P ARTITIONon and and trace the two executions to record the branches taken,indices calculated,and exchanges performed—but not the actual array values ma-nipulated.Argue briefly that the two execution traces are identical.Argue further thatP ARTITION performs the same permutation on both inputs.Solution:P ARTITION takes different branches based only on the comparisons made in thefunction.This is clear by observing line4of the function,as it is the only place wherethe sequence of instructions may differ.As the arrays have identical functionvalues,they must take the same branches,calculate the same indicies and perform thesame exchanges.Consequently P ARTITION will perform the same partition on botharrays,which follows directly as the exchanges performed are identical.Define a sequence to be an input pattern if,for ,and.Define a sequence to be an output pattern ififififWe say that a permutation of satisfies a pattern iffor all.(c)How many input patterns are there?How many output patterns are there?Solution:There are input patterns because we can choose positions out of possible positions to have.There is one()output pattern because the pattern must be exactly negative ones followed by a0,followed byones.(d)How many permutations of satisfy a particular input pattern?How manypermutations of satisfy a particular output pattern?Solution:permutations are possible of to satisfy a particular input pattern.This is the total number of ways to rearrange the elements which have a value ofamongst themselves,and rearrange those with a value of1amongst themselves.Thereare also permutations possible to satisfy a particular output patternfor the same reason.Let be an input pattern,and let be an output pattern.Define to be the set of permutations of that satisfy,and likewise define to be the set of permutations of that satisfy.(e)Argue that P ARTITION implements a bijection from to.(Hint:Use the factfrom group theory that composing afixed permutation with each of the possiblepermutations yields the set of all permutations.)Solution:All members of satisfy and so they all have the same result when the functionis applied to its elements.Therefore by part(b)when all these inputs are given toP ARTITION they are subject to the same ing the hint,we then knowthat after all of the distinct inputs are run through P ARTITION that they will produceall distinct outputs.From part we know that and are thesame size,and also we have proven that P ARTITION is onto,and therefore P ARTITIONmust be a bijection!(f)Suppose that before the call to P ARTITION,the input subarray is a randompermutation of,where.Argue that after P ARTITION,the tworesulting subarrays are random permutations of their respective elements.Solution:Using our solution from part(e),we know that after P ARTITION is run on,we getall values in the set.Therefore we get all permutations of the ones and allpermutations of the negative ones.Furthermore,we get each sub-array permu-tations an equal number of times and so the subarrays are also random permutations.(g)Use induction to show that,under the assumption that all input permutations areequally likely,at each recursive call of Q UICKSORT,every element of be-longing to is equally likely to be the pivot.Solution:The base case for the initial array;we know that it is randomly permuted,and so bypart and each of its subarrays will also be randomly permuted after P ARTITION.Therefore we can inductively apply at each partition to prove that every subarraywill also be randomly permuted.(h)Use the analysis of R ANDOMIZED-Q UICKSORT to conclude that the average-caserunning time of Q UICKSORT on elements is.Solution:By part(g)we know that under the assumption that the input pattern is random everyelement is equally likely to be chosen as the pivot at each recursive call which then pro-duces the same random distribution of quicksort traces as R ANDOMIZED-Q UICKSORT.Therefore as their distribution is the same,the expected-case analysis for R ANDOMIZED-Q UICKSORT will apply to the average case of Q UICKSORT.Therefore the average case of Q UICKSORTalso takes time.Problem2-2.Analysis of-ary heapsA-ary heap is like a binary heap,but(with one possible exception)nonleaf nodes have children instead of2children.(a)How would you represent a-ary heap in an array?Solution:The-ary heap would be similar to a binary heap with the parent and child indexescalculated as follows:th-Child[]whereThe root of the tree would be at index.Alternate Solution:A-ary heap can be represented in a-dimensional array asfollows.The root is kept in,its children are kept in order in through,their children are kept in order in through,and so on.The two procedures that map a node with index to its parent and to its th child(for),respectively,are;D-ARY-P ARENTreturnD-ARY-C HILDreturnTo convince yourself that these procedures really work,verify thatD-ARY-P ARENT D-ARY-C HILDfor any.Notice that the binary heap procedures are a special case of the above procedures when.(b)What is the height of a-ary heap of elements in terms of and?Solution:CORRECTIONA-ary heap would have a height of.We know thatwhich solves to.(c)Give an efficient implementation of E XTRACT-M AX in a-ary max-heap.Analyze itsrunning time in terms of and.Solution:H EAPIFY12for to3if and4then5if6then7Exchange8H EAPIFYThe running time of H EAPIFY is because at each depth we are doing loops,and we recurse to the depth of the tree.In H EAPIFY we compare the the th node and each of its children tofind the maximum value for all of the nodes.Then ifthe maximum child is greater than the th node,we switch the two nodes and recurse on the child.E XTRACT-M AX(A,n)1234H EAPIFY(A,1,n,d)5returnThe running time of this algorithm,is clearly constant work plus the time of H EAPIFY which as shown above is.E XTRACT-M AX works by storing the value of the maximum element,moving the minimum element into the root of the heap,and then calling heapify to restore the heap property.(d)Give an efficient implementation of I NSERT in a-ary max-heap.Analyze its runningtime in terms of and.Solution:See next problem part for I NCREASE-K EY definition.I NSERT123I NCREASE-K EYFrom the following problem part,we know I NCREASE-K EY runs in time, therefore since I NSERT only adds constant time operations it is also.It is rather trivially correct as the algorithm has not changed because all calculations involving the number of children are performed by I NCREASE K EY.(e)Give an efficient implementation of I NCREASE-K EY,whichfirst setsand then updates the-ary max-heap structure appropriately.Analyze its running time in terms of and.Solution:I NCREASE-K EY12if3while and 6。

算法导论第三版_习题_第二章_C语言实现

算法导论第三版_习题_第二章_C语言实现

目录第二章 (2)练习题 (2)2.1-1 (2)2.1-2 (2)2.1-3 (2)2.1-4 (3)2.2-1 (3)2.2-2 (3)2.2-3 (4)2.2-4 (4)2.3-1 (4)2.3-2 (4)2.3-3 (4)2.3-4 (5)2.3-5 (5)2.3-6 (6)*2.3-7 (6)思考题 (6)2-1 ( (6)第二章练习题2.1-1以图2-2为模型,说明INSERTION-SORT在数组A=(31,41,59,26, 41,58〉上的执行过程。

略2.1-2重写过程INSERTION-SORT,使之按非升序(而不是非降序)排序。

//2.1-2.c 插入排序-非升序void InsertionSortNI(int ar[],int n){int i,j,key;for(j=1;j<n;j++){key = ar[j];i = j-1;while(i>=0&& ar[i]<key){ar[i+1]= ar[i];i=i-1;}ar[i+1]= key;}}2.1-3思考下面的查找问题:输入:有n个元素的序列A= (a1,a2,…,an)和一个值v。

输出:下标i(当v=A[i]), 或者特殊值NIL(当v不在A中出现时)。

写出线性查找的伪代码,它扫描整个序列来查找v。

使用一个循环不变式来证明你的算法是正确的。

确保你的循环不变式满足三条必要的性质。

代码://2.1-3.c 线性查找int serchv(int A[],int n,int v){int i;for(i=0;i<n;i++){if(A[i]==v)return i;}return 'NULL';}证明:循环不变式:在每一次for循环开始时,子数组A[0, ..., i-1]中的元素都不等于v;初始化:在第一次迭代之前,i=0,子数组是空数组,易知循环不定式是成立的;保持:在每次循环内部,将A[i] 与v比较,若符合,则返回正确结果i;在每次循环结束时,得知子数组A[0, ..., i-2]不含有v,循环不定式维持成立;递增i,使循环遍历数组中的元素,直到找到v或到达数组尽头;终止:终止条件为1. i>=n 或者2. A[i]==v。

算法导论习题答案 (1)

算法导论习题答案 (1)

Introduction to Algorithms September 24, 2004Massachusetts Institute of Technology 6.046J/18.410J Professors Piotr Indyk and Charles E. Leiserson Handout 7Problem Set 1 SolutionsExercise 1-1. Do Exercise 2.3-7 on page 37 in CLRS.Solution:The following algorithm solves the problem:1.Sort the elements in S using mergesort.2.Remove the last element from S. Let y be the value of the removed element.3.If S is nonempty, look for z=x−y in S using binary search.4.If S contains such an element z, then STOP, since we have found y and z such that x=y+z.Otherwise, repeat Step 2.5.If S is empty, then no two elements in S sum to x.Notice that when we consider an element y i of S during i th iteration, we don’t need to look at the elements that have already been considered in previous iterations. Suppose there exists y j∗S, such that x=y i+y j. If j<i, i.e. if y j has been reached prior to y i, then we would have found y i when we were searching for x−y j during j th iteration and the algorithm would have terminated then.Step 1 takes �(n lg n)time. Step 2 takes O(1)time. Step 3 requires at most lg n time. Steps 2–4 are repeated at most n times. Thus, the total running time of this algorithm is �(n lg n). We can do a more precise analysis if we notice that Step 3 actually requires �(lg(n−i))time at i th iteration.However, if we evaluate �n−1lg(n−i), we get lg(n−1)!, which is �(n lg n). So the total runningi=1time is still �(n lg n).Exercise 1-2. Do Exercise 3.1-3 on page 50 in CLRS.Exercise 1-3. Do Exercise 3.2-6 on page 57 in CLRS.Exercise 1-4. Do Problem 3-2 on page 58 of CLRS.Problem 1-1. Properties of Asymptotic NotationProve or disprove each of the following properties related to asymptotic notation. In each of the following assume that f, g, and h are asymptotically nonnegative functions.� (a) f (n ) = O (g (n )) and g (n ) = O (f (n )) implies that f (n ) = �(g (n )).Solution:This Statement is True.Since f (n ) = O (g (n )), then there exists an n 0 and a c such that for all n √ n 0, f (n ) ←Similarly, since g (n )= O (f (n )), there exists an n � 0 and a c such that for allcg (n ). �f (n ). Therefore, for all n √ max(n 0,n Hence, f (n ) = �(g (n )).�()g n ,0← �),0c 1 � g (n ) ← f (n ) ← cg (n ).n √ n c � 0 (b) f (n ) + g (n ) = �(max(f (n ),g (n ))).Solution:This Statement is True.For all n √ 1, f (n ) ← max(f (n ),g (n )) and g (n ) ← max(f (n ),g (n )). Therefore:f (n ) +g (n ) ← max(f (n ),g (n )) + max(f (n ),g (n )) ← 2 max(f (n ),g (n ))and so f (n ) + g (n )= O (max(f (n ),g (n ))). Additionally, for each n , either f (n ) √max(f (n ),g (n )) or else g (n ) √ max(f (n ),g (n )). Therefore, for all n √ 1, f (n ) + g (n ) √ max(f (n ),g (n )) and so f (n ) + g (n ) = �(max(f (n ),g (n ))). Thus, f (n ) + g (n ) = �(max(f (n ),g (n ))).(c) Transitivity: f (n ) = O (g (n )) and g (n ) = O (h (n )) implies that f (n ) = O (h (n )).Solution:This Statement is True.Since f (n )= O (g (n )), then there exists an n 0 and a c such that for all n √ n 0, �)f ()n ,0← �()g n ,0← f (n ) ← cg (n ). Similarly, since g (n ) = O (h (n )), there exists an n �h (n ). Therefore, for all n √ max(n 0,n and a c � such thatfor all n √ n Hence, f (n ) = O (h (n )).cc�h (n ).c (d) f (n ) = O (g (n )) implies that h (f (n )) = O (h (g (n )).Solution:This Statement is False.We disprove this statement by giving a counter-example. Let f (n ) = n and g (n ) = 3n and h (n )=2n . Then h (f (n )) = 2n and h (g (n )) = 8n . Since 2n is not O (8n ), this choice of f , g and h is a counter-example which disproves the theorem.(e) f(n)+o(f(n))=�(f(n)).Solution:This Statement is True.Let h(n)=o(f(n)). We prove that f(n)+o(f(n))=�(f(n)). Since for all n√1, f(n)+h(n)√f(n), then f(n)+h(n)=�(f(n)).Since h(n)=o(f(n)), then there exists an n0such that for all n>n0, h(n)←f(n).Therefore, for all n>n0, f(n)+h(n)←2f(n)and so f(n)+h(n)=O(f(n)).Thus, f(n)+h(n)=�(f(n)).(f) f(n)=o(g(n))and g(n)=o(f(n))implies f(n)=�(g(n)).Solution:This Statement is False.We disprove this statement by giving a counter-example. Consider f(n)=1+cos(�≈n)and g(n)=1−cos(�≈n).For all even values of n, f(n)=2and g(n)=0, and there does not exist a c1for which f(n)←c1g(n). Thus, f(n)is not o(g(n)), because if there does not exist a c1 for which f(n)←c1g(n), then it cannot be the case that for any c1>0and sufficiently large n, f(n)<c1g(n).For all odd values of n, f(n)=0and g(n)=2, and there does not exist a c for which g(n)←cf(n). By the above reasoning, it follows that g(n)is not o(f(n)). Also, there cannot exist c2>0for which c2g(n)←f(n), because we could set c=1/c2if sucha c2existed.We have shown that there do not exist constants c1>0and c2>0such that c2g(n)←f(n)←c1g(n). Thus, f(n)is not �(g(n)).Problem 1-2. Computing Fibonacci NumbersThe Fibonacci numbers are defined on page 56 of CLRS asF0=0,F1=1,F n=F n−1+F n−2for n√2.In Exercise 1-3, of this problem set, you showed that the n th Fibonacci number isF n=�n−� n,�5where �is the golden ratio and �is its conjugate.A fellow 6.046 student comes to you with the following simple recursive algorithm for computing the n th Fibonacci number.F IB(n)1 if n=02 then return 03 elseif n=14 then return 15 return F IB(n−1)+F IB(n−2)This algorithm is correct, since it directly implements the definition of the Fibonacci numbers. Let’s analyze its running time. Let T(n)be the worst-case running time of F IB(n).1(a) Give a recurrence for T(n), and use the substitution method to show that T(n)=O(F n).Solution: The recurrence is: T(n)=T(n−1)+T(n−2)+1.We use the substitution method, inducting on n. Our Induction Hypothesis is: T(n)←cF n−b.To prove the inductive step:T(n)←cF n−1+cF n−2−b−b+1← cF n−2b+1Therefore, T(n)←cF n−b+1provided that b√1. We choose b=2and c=10.∗{For the base case consider n0,1}and note the running time is no more than10−2=8.(b) Similarly, show that T(n)=�(F n), and hence, that T(n)=�(F n).Solution: Again the recurrence is: T(n)=T(n−1)+T(n−2)+1.We use the substitution method, inducting on n. Our Induction Hypothesis is: T(n)√F n.To prove the inductive step:T(n)√F n−1+F n−2+1√F n+1Therefore, T(n)←F n. For the base case consider n∗{0,1}and note the runningtime is no less than 1.1In this problem, please assume that all operations take unit time. In reality, the time it takes to add two num­bers depends on the number of bits in the numbers being added (more precisely, on the number of memory words). However, for the purpose of this problem, the approximation of unit time addition will suffice.Professor Grigori Potemkin has recently published an improved algorithm for computing the n th Fibonacci number which uses a cleverly constructed loop to get rid of one of the recursive calls. Professor Potemkin has staked his reputation on this new algorithm, and his tenure committee has asked you to review his algorithm.F IB�(n)1 if n=02 then return 03 elseif n=14 then return 15 6 7 8 sum �1for k�1to n−2do sum �sum +F IB�(k) return sumSince it is not at all clear that this algorithm actually computes the n th Fibonacci number, let’s prove that the algorithm is correct. We’ll prove this by induction over n, using a loop invariant in the inductive step of the proof.(c) State the induction hypothesis and the base case of your correctness proof.Solution: To prove the algorithm is correct, we are inducting on n. Our inductionhypothesis is that for all n<m, Fib�(n)returns F n, the n th Fibonacci number.Our base case is m=2. We observe that the first four lines of Potemkin guaranteethat Fib�(n)returns the correct value when n<2.(d) State a loop invariant for the loop in lines 6-7. Prove, using induction over k, that your“invariant” is indeed invariant.Solution: Our loop invariant is that after the k=i iteration of the loop,sum=F i+2.We prove this induction using induction over k. We assume that after the k=(i−1)iteration of the loop, sum=F i+1. Our base case is i=1. We observe that after thefirst pass through the loop, sum=2which is the 3rd Fibonacci number.To complete the induction step we observe that if sum=F i+1after the k=(i−1)andif the call to F ib�(i)on Line 7 correctly returns F i(by the induction hypothesis of ourcorrectness proof in the previous part of the problem) then after the k=i iteration ofthe loop sum=F i+2. This follows immediately form the fact that F i+F i+1=F i+2.(e) Use your loop invariant to complete the inductive step of your correctness proof.Solution: To complete the inductive step of our correctness proof, we must show thatif F ib�(n)returns F n for all n<m then F ib�(m)returns m. From the previous partwe know that if F ib�(n)returns F n for all n<m, then at the end of the k=i iterationof the loop sum=F i+2. We can thus conclude that after the k=m−2iteration ofthe loop, sum=F m which completes our correctness proof.(f) What is the asymptotic running time, T�(n), of F IB�(n)? Would you recommendtenure for Professor Potemkin?Solution: We will argue that T�(n)=�(F n)and thus that Potemkin’s algorithm,F ib�does not improve upon the assymptotic performance of the simple recurrsivealgorithm, F ib. Therefore we would not recommend tenure for Professor Potemkin.One way to see that T�(n)=�(F n)is to observe that the only constant in the programis the 1 (in lines 5 and 4). That is, in order for the program to return F n lines 5 and 4must be executed a total of F n times.Another way to see that T�(n)=�(F n)is to use the substitution method with thehypothesis T�(n)√F n and the recurrence T�(n)=cn+�n−2T�(k).k=1Problem 1-3. Polynomial multiplicationOne can represent a polynomial, in a symbolic variable x, with degree-bound n as an array P[0..n] of coefficients. Consider two linear polynomials, A(x)=a1x+a0and B(x)=b1x+b0, where a1, a0, b1, and b0are numerical coefficients, which can be represented by the arrays [a0,a1]and [b0,b1], respectively. We can multiply A and B using the four coefficient multiplicationsm1=a1·b1,m2=a1·b0,m3=a0·b1,m4=a0·b0,as well as one numerical addition, to form the polynomialC(x)=m1x2+(m2+m3)x+m4,which can be represented by the array[c0,c1,c2]=[m4,m3+m2,m1].(a) Give a divide-and-conquer algorithm for multiplying two polynomials of degree-bound n,represented as coefficient arrays, based on this formula.Solution:We can use this idea to recursively multiply polynomials of degree n−1, where n isa power of 2, as follows:Let p(x)and q(x)be polynomials of degree n−1, and divide each into the upper n/2 and lower n/2terms:p(x)=a(x)x n/2+b(x),q(x)=c(x)x n/2+d(x),where a(x), b(x), c(x), and d(x)are polynomials of degree n/2−1. The polynomial product is thenp(x)q(x)=(a(x)x n/2+b(x))(c(x)x n/2+d(x))=a(x)c(x)x n+(a(x)d(x)+b(x)c(x))x n/2+b(x)d(x).The four polynomial products a(x)c(x), a(x)d(x), b(x)c(x), and b(x)d(x)are com­puted recursively.(b) Give and solve a recurrence for the worst-case running time of your algorithm.Solution:Since we can perform the dividing and combining of polynomials in time �(n), re­cursive polynomial multiplication gives us a running time ofT(n)=4T(n/2)+�(n)=�(n2).(c) Show how to multiply two linear polynomials A(x)=a1x+a0and B(x)=b1x+b0using only three coefficient multiplications.Solution:We can use the following 3 multiplications:m1=(a+b)(c+d)=ac+ad+bc+bd,m2=ac,m3=bd,so the polynomial product is(ax+b)(cx+d)=m2x2+(m1−m2−m3)x+m3.� (d) Give a divide-and-conquer algorithm for multiplying two polynomials of degree-bound nbased on your formula from part (c).Solution:The algorithm is the same as in part (a), except for the fact that we need only compute three products of polynomials of degree n/2 to get the polynomial product.(e) Give and solve a recurrence for the worst-case running time of your algorithm.Solution:Similar to part (b):T (n )=3T (n/2) + �(n )lg 3)= �(n �(n 1.585)Alternative solution Instead of breaking a polynomial p (x ) into two smaller poly­nomials a (x ) and b (x ) such that p (x )= a (x ) + x n/2b (x ), as we did above, we could do the following:Collect all the even powers of p (x ) and substitute y = x 2 to create the polynomial a (y ). Then collect all the odd powers of p (x ), factor out x and substitute y = x 2 to create the second polynomial b (y ). Then we can see thatp (x ) = a (y ) + x b (y )· Both a (y ) and b (y ) are polynomials of (roughly) half the original size and degree, and we can proceed with our multiplications in a way analogous to what was done above.Notice that, at each level k , we need to compute y k = y 2 (where y 0 = x ), whichk −1 takes time �(1) per level and does not affect the asymptotic running time.。

算法导论 第三版 第一章 答案 英

算法导论 第三版 第一章 答案 英

Chapter1Michelle Bodnar,Andrew LohrApril12,2016Exercise1.1-1An example of a real world situation that would require sorting would be if you wanted to keep track of a bunch of people’sfile folders and be able to look up a given name quickly.A convex hull might be needed if you needed to secure a wildlife sanctuary with fencing and had to contain a bunch of specific nesting locations.Exercise1.1-2One might measure memory usage of an algorithm,or number of people required to carry out a single task.Exercise1.1-3An array.It has the limitation of requiring a lot of copying when re-sizing, inserting,and removing elements.Exercise1.1-4They are similar since both problems can be modeled by a graph with weighted edges and involve minimizing distance,or weight,of a walk on the graph.They are different because the shortest path problem considers only two vertices,whereas the traveling salesman problem considers minimizing the weight of a path that must include many vertices and end where it began.Exercise1.1-5If you were for example keeping track of terror watch suspects,it would be unacceptable to have it occasionally bringing up a wrong decision as to whether a person is on the list or not.It would befine to only have an approximate solution to the shortest route on which to drive,an extra little bit of driving is not that bad.1Exercise1.2-1A program that would pick out which music a user would like to listen tonext.They would need to use a bunch of information from historical and pop-ular preferences in order to maximize.Exercise1.2-2We wish to determine for which values of n the inequality8n2<64n log2(n)holds.This happens when n<8log2(n),or when n≤43.In other words,insertion sort runs faster when we’re sorting at most43items.Otherwise mergesort is faster.Exercise1.2-3We want that100n2<2n.note that if n=14,this becomes100(14)2=19600>214=16384.For n=15it is100(15)2=22500<215=32768.So,the answer is n=15.Problem1-1We assume a30day month and365day year.1Second1Minute1Hour1Day1Month1Year1Century lg n21×10626×10723.6×10928.64×101022.592×101223.1536×101323.15576×1015√n1×10123.6×10151.29×10197.46×10216.72×10249.95×10269.96×1030 n1×1066×1073.6×1098.64×10102.59×10123.15×10133.16×1015 n lg n1894818.64×1064.18×1088.69×1092.28×10112.54×10122.20×1014 n210007745600002939381609968561569256176151 n3100391153244201373631593146679 2n19253136414451n!91112131516172。

Ch10算法导论第三版第十章答案英

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。

算法导论第三版答案

算法导论第三版答案
Solution to Exercise 2.3-5
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.

算法导论答案Ch3

算法导论答案Ch3
n→∞
f (n) =∞ g (n)
Ω(g (n, m)) = {f (n, m) : there exist positive constants c, n0 , and m0 such that f (n, m) ≥ cg (n, m) for all n ≥ n0 or m ≥ m0 }
Θ(g (n, m)) = {f (n, m) : there exist positive constants c1 , c2 , n0 , and m0 such that c1 g (n, m) ≤ f (n, m) ≤ c2 g (n, m) for all n ≥ n0 or m ≥ m0 } Exercise 3.2-1 Let n1 < n2 be arbitrary. From f and g being monatonic increasing, we know f (n1 ) < f (n2 ) and g (n1 ) < g (n2 ). So f (n1 ) + g (n1 ) < f (n2 ) + g (n1 ) < f (n2 ) + g (n2 ) 2
n→∞
2e n
n
≤ lim
n→∞
2e n
n
1 =0 2n
nn 1 en n −.5 n √ = lim √ e = lim O ( n ) e ≥ lim 1 n→∞ n! n→∞ n→∞ c1 n n→∞ 2πn(1 + Θ( n )) lim ≥ lim en en = lim =∞ n→∞ c1 n n→∞ c1
n a/b n if and only if if and only if n − 21 /b ≥ −a if and only if n + a ≥ (1/2) (n + a)b ≥ cnb . Therefore (n + a)b = Ω(nb ). By Theorem 3.1, (n + a)b = Θ(nb ).

算法导论中文版答案

算法导论中文版答案

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

编译原理-第三版-何炎祥-第二章习题答案

编译原理-第三版-何炎祥-第二章习题答案

2.1 写出下列文法所确定的语言:①、文法G = ({D},{0,1,2,3,4,5,6,7,8,9},P,D)其中,P={D→0|1|2|3|4|5|6|7|8|9};该文法定义的是0到9这10个数字{0,1,2,3,4,5,6,7,8,9};②、文法G = ({B,L,D},{0,1,2,3,4,5,6,7,8,9},P,B);其中,P = {B→D|L,L→1|2|3|4|5|6|7|89,D→0|L};该文法定义的是0到9这10个数字{0,1,2,3,4,5,6,7,8,9};③、文法G=({S,A},{a,b},P,S)其中,P={S→Aa,A→bA|a}。

该文件定义的是{b a a2|n≥0};2.2 ①因为语言的句子要求由3的整数倍的a组成,所以在构造产生式时,要保证每次产生的a 的个数是3,得到文法G[s]:s→aaa|Saaa ②因为符号串中a、b的个数没有直接关系,所以,将句子分成两部分:aaa和b2m-1,分别进行构造,然后再合并,可由产生式A→a|aA 得到aa,而由产生式B→b|bbB得到b2m-1,由于n≥1,m≥1,所以得到文法G【s】:S→ABA →a|aAB→b|bbB ③因为句子中a和B的个数一样多,且a全部在句子的前半部分,b全部在句子的后半部分,所以在构造产生式时,可让a和b对称出现,得文法G【s】:s→aSb|ab ④因为句子中a、b、c的个数没有直接关系,所以分别构造生成an。

Bmck的产生式,然后再合成,可由产生式a→aA|。

得到bm,再有产生式c→cc|、得到ck,⑤文法为GS:S→(+|-)(ABC|2|4|6|8)|0 C→02468 B→BAB0 A→123456789 ⑥能被5整除的整数的末尾数必定是0或5,所以只要保证生成的整数末位数字是0或5即可,据此,构造描述能被5整除集合的文法如下:GS:S→(+|-)A(0|5)A→0123456789 如果还要求整数除0外,均不以0开头,则文法为GS:S→(+|-)A(0|5)(0|5)⑦由于文法的句子a∈{a,b},因此文法的句子可分解为两种情形;以a打头的符号串以b打头的符号串于是只要在构造产生式时保证每次产生相同个数的a和b即可,可以构造文法如下LGS:S →aSbbSaabSbaSSba 2.4 0型文法2.5 P={S→aD|eE,D→bf,F→dB,A→bc,B→d} 2.6、①3274的最左推导为:N→ND→NDD→NDDD→DDDD→3DDD→32DD→327D→3274 ①3274的最右推导为:N→ND→N4→ND4→N74→ND74→N274→D274→3274 的最左推导为:②65173的最左推导为:N→ND→NDD→NDDD→DDDDD→6DDDD→65DDD→651DD→65173 65173的最右推导为:的最右推导为:N→ND→N3→ND3→ND73→ND73→ND73→ND173→65173 2.7、要判断文法是否具有二义性,只要判断文法是否定义有这样的句子,该句子对应着两颗以上的语法树,或者说有两个以上不同的最右推导,或者说在对该句子进行规范规约的过程中,其规范句型的句柄不唯一。

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

Chapter2Michelle Bodnar,Andrew LohrApril12,2016Exercise2.1-1314159264158314159264158314159264158263141594158263141415958263141415859Exercise2.1-2Algorithm1Non-increasing Insertion-Sort(A)1:for j=2to A.length do2:key=A[j]3://Insert A[j]into the sorted sequence A[1..j−1].4:i=j−15:while i>0and A[i]<key do6:A[i+1]=A[i]7:i=i−18:end while9:end for10:A[i+1]=keyExercise2.1-3On each iteration of the loop body,the invariant upon entering is that there is no index k<j so that A[k]=v.In order to proceed to the next iteration of the loop,we need that for the current value of j,we do not have A[j]=v.If the loop is exited by line5,then we have just placed an acceptable value in i on the previous line.If the loop is exited by exhausting all possible values of j, then we know that there is no index that has value j,and so leaving NIL in i is correct.11:i=NIL2:for j=1to A.length do3:if A[j]=v then4:i=j5:return i6:end if7:return i8:end forExercise2.1-4Input:two n-element arrays A and B containing the binary digits of two numbers a and b.Output:an(n+1)-element array C containing the binary digits of a+b.Algorithm2Adding n-bit Binary Integers1:carry=02:for i=1to n do3:C[i]=(A[i]+B[i]+carry)(mod2)4:if A[i]+B[i]+carry≥2then5:carry=16:else7:carry=08:end if9:end for10:C[n+1]=carryExercise2.2-1n3/1000−100n2−100n+3∈Θ(n3)Exercise2.2-2Input:An n-element array A.Output:The array A with its elements rearranged into increasing order.The loop invariant of selection sort is as follows:At each iteration of the for loop of lines1through10,the subarray A[1..i−1]contains the i−1smallest elements of A in increasing order.After n−1iterations of the loop,the n−1 smallest elements of A are in thefirst n−1positions of A in increasing order, so the n th element is necessarily the largest element.Therefore we do not need to run the loop afinal time.The best-case and worst-case running times of selection sort areΘ(n2).This is because regardless of how the elements are initially arranged,on the i th iteration of the main for loop the algorithm always inspects each of the remaining n−i elements tofind the smallest one remaining.2Algorithm3Selection Sort1:2:min=i3:for j=i+1to n do4://Find the index of the i th smallest element 5:if A[j]<A[min]then6:min=j7:end if8:end for9:Swap A[min]and A[i]10:end forThis yields a running time ofn−1i=1n−i=n(n−1)−n−1i=1i=n2−n−n2−n2=n2−n2=Θ(n2).Exercise2.2-3Suppose that every entry has probability p of being the element looked for. Then,we will only check k elements if the previous k−1positions were not the element being looked for,and the k th position is the desired value.Taking the expected value of this distribution we get it to be(1−p)A.length+A.lengthk=1k(1−p)k−1p kExercise2.2-4For a good best-case running time,modify an algorithm tofirst randomly produce output and then check whether or not it satisfies the goal of the al-gorithm.If so,produce this output and halt.Otherwise,run the algorithm as usual.It is unlikely that this will be successful,but in the best-case the running time will only be as long as it takes to check a solution.For example,we could modify selection sort tofirst randomly permute the elements of A,then check if they are in sorted order.If they are,output A.Otherwise run selection sort as usual.In the best case,this modified algorithm will have running timeΘ(n).Exercise2.3-1If we start with reading across the bottom of the tree and then go up levelby level.34152263857949 34126523857949 32641529384957 392638414952573Exercise2.3-2The following is a rewrite of MERGE which avoids the use of sentinels.Much like MERGE,it begins by copying the subarrays of A to be merged into arrays L and R.At each iteration of the while loop starting on line13it selects the next smallest element from either L or R to place into A.It stops if either L or R runs out of elements,at which point it copies the remainder of the other subarray into the remaining spots of A.Algorithm4Merge(A,p,q,r)1:12:n2=r−q3:let L[1,..n1]and R[1..n2]be new arrays4:for i=1to n1do5:L[i]=A[p+i−1]6:end for7:for j=1to n2do8:R[j]=A[q+j]9:end for10:i=111:j=112:k=p13:while i=n1+1and j=n2+1do14:if L[i]≤R[j]then15:A[k]=L[i]16:i=i+117:else A[k]=R[j]18:j=j+119:end if20:k=k+121:end while22:if i==n1+1then23:for m=j to n2do24:A[k]=R[m]25:k=k+126:end for27:end if28:if j==n2+1then29:for m=i to n1do30:A[k]=L[m]31:k=k+132:end for33:end if4Exercise2.3-3Since n is a power of two,we may write n=2k.If k=1,T(2)=2=2lg(2). Suppose it is true for k,we will show it is true for k+1.T(2k+1)=2T2k+12+2k+1=2T2k+2k+1=2(2k lg(2k))+2k+1=k2k+1+2k+1=(k+1)2k+1=2k+1lg(2k+1)=n lg(n)Exercise2.3-4Let T(n)denote the running time for insertion sort called on an array of size n.We can express T(n)recursively asT(n)=Θ(1)if n≤cT(n−1)I(n)otherwisewhere I(n)denotes the amount of time it takes to insert A[n]into the sorted array A[1..n−1].As seen in exercise2.3-5,I(n)isΘ(log n).Exercise2.3-5The following recursive algorithm gives the desired result when called with a=1and b=n.1:BinSearch(a,b,v)2:if then a>b3:return NIL4:end if5:m= a+b26:if then m=v7:return m8:end if9:if then m<v10:return BinSearch(a,m,v)11:end if12:return BinSearch(m+1,b,v)Note that the initial call should be BinSearch(1,n,v).Each call results in a constant number of operations plus a call to a problem instance where the quantity b−a falls by at least a factor of two.So,the runtime satisfies the recurrence T(n)=T(n/2)+c.So,T(n)∈Θ(lg(n))Exercise2.3-65A binary search wouldn’t improve the worst-case running time.Insertion sort has to copy each element greater than key into its neighboring spot in the array.Doing a binary search would tell us how many how many elements need to be copied over,but wouldn’t rid us of the copying needed to be done. Exercise2.3-71:Use Merge Sort to sort the array A in timeΘ(n lg(n))2:i=13:j=n4:while i<j do5:if A[j]+A[j]=S then6:return true7:end if8:if A[i]+A[j]<S then9:i=i+110:end if11:if A[i]+A[j]>S then12:j=j−113:end if14:end while15:return falseWe can see that the while loop gets run at most O(n)times,as the quantity j−i starts at n−1and decreases at each step.Also,since the body only consists of a constant amount of work,all of lines2-15takes only O(n)time.So,the runtime is dominated by the time to perform the sort,which isΘ(n lg(n)). We will prove correctness by a mutual induction.Let m i,j be the proposition A[i]+A[j]<S and M i,j be the proposition A[i]+A[j]>S.Note that because the array is sorted,m i,j⇒∀k<j,m i,k,and M i,j⇒∀k>i,M k,j.Our program will obviously only output true in the case that there is a valid i and j.Now,suppose that our program output false,even though there were some i,j that was not considered for which A[i]+A[j]=S.If we have i>j, then swap the two,and the sum will not change,so,assume i≤j.we now have two cases:Case1∃k,(i,k)was considered and j<k.In this case,we take the smallest such k.The fact that this is nonzero meant that immediately after considering it,we considered(i+1,k)which means m i,k this means m i,jCase2∃k,(k,j)was considered and k<i.In this case,we take the largest such k.The fact that this is nonzero meant that immediately after considering it,we considered(k,j-1)which means M k,j this means M i,jNote that one of these two cases must be true since the set of considered points separates{(m,m ):m≤m <n}into at most two regions.If you are in the region that contains(1,1)(if nonempty)then you are in Case1.If you6are in the region that contains(n,n)(if non-empty)then you are in case2. Problem2-1a.The time for insertion sort to sort a single list of length k isΘ(k2),so,n/kof them will take timeΘ(nkk2)=Θ(nk).b.Suppose we have coarseness k.This meas we can just start using the usualmerging procedure,except starting it at the level in which each array has size at most k.This means that the depth of the merge tree is lg(n)−lg(k)= lg(n/k).Each level of merging is still time cn,so putting it together,the merging takes timeΘ(n lg(n/k)).c.Viewing k as a function of n,as long as k(n)∈O(lg(n)),it has the sameasymptotics.In particular,for any constant choice of k,the asymptotics are the same.d.If we optimize the previous expression using our calculus1skills to get k,wehave that c1n−nc2k =0where c1and c2are the coeffients of nk and n lg(n/k)hidden by the asymptotics notation.In particular,a constant choice of k is optimal.In practice we couldfind the best choice of this k by just trying and timing for various values for sufficiently large n.Problem2-21.We need to prove that A contains the same elements as A,which is easilyseen to be true because the only modification we make to A is swapping its elements,so the resulting array must contain a rearrangement of the elements in the original array.2.The for loop in lines2through4maintains the following loop invari-ant:At the start of each iteration,the position of the smallest element of A[i..n]is at most j.This is clearly true prior to thefirst iteration because the position of any element is at most A.length.To see that each iter-ation maintains the loop invariant,suppose that j=k and the position of the smallest element of A[i..n]is at most k.Then we compare A[k]to A[k−1].If A[k]<A[k−1]then A[k−1]is not the smallest element of A[i..n],so when we swap A[k]and A[k−1]we know that the smallest element of A[i..n]must occur in thefirst k−1positions of the subarray, the maintaining the invariant.On the other hand,if A[k]≥A[k−1]then the smallest element can’t be A[k].Since we do nothing,we conclude that the smallest element has position at most k−1.Upon termination,the smallest element of A[i..n]is in position i.73.The for loop in lines1through4maintain the following loop invariant:At the start of each iteration the subarray A[1..i−1]contains the i−1smallest elements of A in sorted order.Prior to thefirst iteration i=1,and thefirst0elements of A are trivially sorted.To see that each iterationmaintains the loop invariant,fix i and suppose that A[1..i−1]containsthe i−1smallest elements of A in sorted order.Then we run the loop inlines2through4.We showed in part b that when this loop terminates,the smallest element of A[i..n]is in position i.Since the i−1smallestelements of A are already in A[1..i−1],A[i]must be the i th smallestelement of A.Therefore A[1..i]contains the i smallest elements of A insorted order,maintaining the loop invariant.Upon termination,A[1..n]contains the n elements of A in sorted order as desired.4.The i th iteration of the for loop of lines1through4will cause n−iiterations of the for loop of lines2through4,each with constant timeexecution,so the worst-case running time isΘ(n2).This is the same asthat of insertion sort;however,bubble sort also has best-case running timeΘ(n2)whereas insertion sort has best-case running timeΘ(n).Problem2-3a.If we assume that the arithmetic can all be done in constant time,then sincethe loop is being executed n times,it has runtimeΘ(n).b.1:y=02:for i=0to n do3:y i=x4:for j=1to n do5:y i=y i x6:end for7:y=y+a i y i8:end forThis code has runtimeΘ(n2)because it has to compute each of the powers of x.This is slower than Horner’s rule.c.Initially,i=n,so,the upper bound of the summation is−1,so the sumevaluates to0,which is the value of y.For preservation,suppose it is true for an i,then,y=a i+x n−(i+1)k=0a k+i+1x k=a i+xn−ik=1a k+i x k−1=n−ik=0a k+i x kAt termination,i=0,so is summing up to n−1,so executing the body of the loop a last time gets us the desiredfinal result.8d.We just showed that the algorithm evaluatedΣnk=0a k x k.This is the value ofthe polynomial evaluated at x.Problem2-4a.Thefive inversions are(2,1),(3,1),(8,6),(8,1),and(6,1).b.The n-element array with the most inversions is n,n−1,...,2,1 .It hasn−1+n−2+...+2+1=n(n−1)2inversions.c.The running time of insertion sort is a constant times the number of inver-sions.Let I(i)denote the number of j<i such that A[j]>A[i].Thenni=1I(i)equals the number of inversions in A.Now consider the whileloop on lines5-7of the insertion sort algorithm.The loop will execute once for each element of A which has index less than j is larger than A[j].Thus, it will execute I(j)times.We reach this while loop once for each iteration of the for loop,so the number of constant time steps of insertion sort is nj=1I(j)which is exactly the inversion number of A.d.We’ll call our algorithm M.Merge-Sort for Modified Merge Sort.In additionto sorting A,it will also keep track of the number of inversions.The algorithm works as follows.When we call M.Merge-Sort(A,p,q)it sorts A[p..q]and returns the number of inversions in the elements of A[p..q],so left and right track the number of inversions of the form(i,j)where i and j are both in the same half of A.When M.Merge(A,p,q,r)is called,it returns the number of inversions of the form(i,j)where i is in thefirst half of the array and j is in the second half.Summing these up gives the total number of inversions in A.The runtime is the same as that of Merge-Sort because we only add an additional constant-time operation to some of the iterations of some of the loops.Since Merge isΘ(n log n),so is this algorithm.Algorithm5M.Merge-Sort(A,p,r)if p<r thenq= (p+r)/2left=M.Merge−Sort(A,p,q)right=M.Merge−Sort(A,q+1,r)inv=M.Merge(A,p,q,r)+left+rightreturn invend ifreturn09Algorithm6M.Merge(A,p,q,r)inv=0n1=q−p+1n2=r−qlet L[1,..n1]and R[1..n2]be new arraysfor i=1to n1doL[i]=A[p+i−1]end forfor j=1to n2doR[j]=A[q+j]end fori=1j=1k=pwhile i=n1+1and j=n2+1doif L[i]≤R[j]thenA[k]=L[i]i=i+1else A[k]=R[j]inv=inv+j//This keeps track of the number of inversions between the left and right arrays.j=j+1end ifk=k+1end whileif i==n1+1thenfor m=j to n2doA[k]=R[m]k=k+1end forend ifif j==n2+1thenfor m=i to n1doA[k]=L[m]inv=inv+n2//Tracks inversions once we have exhausted the right array.At this point,every element of the right array contributes an inversion.k=k+1end forend ifreturn inv10。

相关文档
最新文档