Skip to content

Latest commit

 

History

History
34 lines (20 loc) · 1.77 KB

File metadata and controls

34 lines (20 loc) · 1.77 KB

Exercises 9.1-1


Show that the second smallest of n elements can be found with comparisons in the worst case. (Hint: Also find the smallest element.)

Answer

code tells everything!

想法大致是这样的:首先由下往上建一颗二叉树,每个节点保存一对的最小值,这样总共需要n-1次比较.这棵树的顶点是最小值.第二小元素肯定在生成顶点的路径上,因为第二小元素只会被最小元素击败,所以两节点肯定交手过一次.因为树的高度不过超过 image 所以需要image - 1 次比较.因此总共需要image

First we build a BST from bottom to top,each node contains the smaller one of a pair, we need n-1 comparisions to build BST. The top of this BST is minimum, then the second smallest must be in the path to generate the top. Because the second smallest can only be defeated by the smallest one. Because the height of BST does not exceed image so we need image - 1 comparisions.The total times isimage

Exercises 9.1-2


Show that image comparisons are necessary in the worst case to find both the maximum and minimum of n numbers. (Hint: Consider how many numbers are potentially either the maximum or minimum, and investigate how a comparison affects these counts.)

Answer

As mentioned before, if n is odd,then we need image

If n is even,then we need 3n/2-2

image is the same format.


Follow @louis1992 on github to help finish this task.