algorithm - Finding largest and second-largest out of N numbers -
given n numbers, how find largest , second largest number using @ n+log(n) comparisons?
note it's not o(n+log(n)), n+log(n) comparisons.
pajton gave comment.
let me elaborate.
as pajton said, can done tournament selection.
think of knock out singles tennis tournament, player abilities have strict order , outcome of match decided solely order.
in first round half people eliminated. in next round half etc (with byes possible).
ultimately winner decided in last , final round.
this can viewed tree.
each node of tree winner of match between children of node.
the leaves players. winner of first round parents of leaves etc.
this complete binary tree on n nodes.
now follow path of winner. there log n matches winner has played. consider losers of log n matches. second best must best among those.
the winner decided in n-1 matches (you knock out 1 per match) , winner among logn decided in logn -1 matches.
thus can decide largest , second largest in n+logn - 2 compares.
in fact, can proven optimal. in comparison scheme in worst case, winner have play logn matches.
to prove assume point system after match winner gets points of loser. start out 1 point each.
at end final winner has n points.
now given algorithm, arranged player more points winner. since points of person @ double in match in scenario, require @ least log n matches played winner in worst case.
Comments
Post a Comment