算法导论 第三版 第二章 答案 英
算法导论 答案 (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)是证明算法正确性的一个重要工具。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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。