Show that the second smallest of n elements can be found with comparisons in the worst case. (Hint: Also find the smallest element.)
code tells everything!
想法大致是这样的:首先由下往上建一颗二叉树,每个节点保存一对的最小值,这样总共需要n-1次比较.这棵树的顶点是最小值.第二小元素肯定在生成顶点的路径上,因为第二小元素只会被最小元素击败,所以两节点肯定交手过一次.因为树的高度不过超过 所以需要 - 1 次比较.因此总共需要
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 so we need - 1 comparisions.The total times is
Show that 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.)
As mentioned before, if n is odd,then we need
If n is even,then we need 3n/2-2
Follow @louis1992 on github to help finish this task.