算法导论学习笔记-找数组中第二小的数

The smallest of n numbers can be found with n − 1 comparisons by conducting a

tournament as follows: Compare all the numbers in pairs. Only the smaller of each

pair could possibly be the smallest of all n, so the problem has been reduced to that

of Þnding the smallest of n/2 numbers. Compare those numbers in pairs, and so

on, until there’s just one number left, which is the answer.

To see that this algorithm does exactly n −1 comparisons, notice that each number

except the smallest loses exactly once. To show this more formally, draw a binary

tree of the comparisons the algorithm does. The n numbers are the leaves, and each

number that came out smaller in a comparison is the parent of the two numbers that

were compared. Each non-leaf node of the tree represents a comparison, and there

are n − 1 internal nodes in an n-leaf full binary tree (see Exercise (B.5-3)), so

exactly n − 1 comparisons are made.

In the search for the smallest number, the second smallest number must have come

out smallest in every comparison made with it until it was eventually compared

with the smallest. So the second smallest is among the elements that were compared

with the smallest during the tournament. To Þnd it, conduct another tournament

(as above) to Þnd the smallest of these numbers. At most lg n (the height

of the tree of comparisons) elements were compared with the smallest, so Þnding

the smallest of these takes lg n − 1 comparisons in the worst case.

The total number of comparisons made in the two tournaments was

n − 1 + lg n − 1 = n + lg n − 2

in the worst case.

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值