9.1-2 Find the second smallest of n elements.

来源:互联网 发布:阿里云 mysql 编辑:程序博客网 时间:2024/06/05 21:09

9.1-1

Show that the second smallest of n elements can be found with n + lg n - 2

comparisons in the worst case. (Hint: Also find the smallest element.)


I thinked about it for some time and can't work out the answer. First I want to borrow the idea from the text, kepp track of both the smallest and second smallest element in the array. But found that in worst case that will degrade to O(2n). I decided to look for an answer from the Internet.


Internet Solution:

1. get the smallest between each adjacent pairs and get n/2 elements.

2. again get the smallest from the n/2 elements using the same method.

3. repeat the method iteratively until we have the smallest element.

4. in the process we track the elements that has been compared the the smallest, and the second smallest must in them.

Get the smallest from these elements, that's the second smallest.


Analysis:

1. This is the method that's used in a match. Get the champion using the groups of two method, and get the second from the ones who's defeated by the champion.

2. Exchange space for time. Remember the intermediate information, and use(cache) that for the final or other intermediate purpose.



原创粉丝点击