Find the 2nd largest element in an array with minimum number of comparisons

后端 未结 24 1330
清酒与你
清酒与你 2020-11-28 01:03

For an array of size N, what is the number of comparisons required?

24条回答
  •  孤独总比滥情好
    2020-11-28 01:17

    You can find the second largest value with at most 2·(N-1) comparisons and two variables that hold the largest and second largest value:

    largest := numbers[0];
    secondLargest := null
    for i=1 to numbers.length-1 do
        number := numbers[i];
        if number > largest then
            secondLargest := largest;
            largest := number;
        else
            if number > secondLargest then
                secondLargest := number;
            end;
        end;
    end;
    

提交回复
热议问题