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

合集下载

算法导论 答案 (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答案

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语言实现

目录第二章 (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、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  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。

相关文档
最新文档