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

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

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

24条回答
  •  半阙折子戏
    2020-11-28 01:20

    Sorry, JS code...

    Tested with the two inputs:

    a = [55,11,66,77,72];
    a = [ 0, 12, 13, 4, 5, 32, 8 ];
    
    var first = Number.MIN_VALUE;
    var second = Number.MIN_VALUE;
    for (var i = -1, len = a.length; ++i < len;) {
        var dist = a[i];
        // get the largest 2
        if (dist > first) {
            second = first;
            first = dist;
        } else if (dist > second) { // && dist < first) { // this is actually not needed, I believe
            second = dist;
        }
    }
    
    console.log('largest, second largest',first,second);
    largest, second largest 32 13
    

    This should have a maximum of a.length*2 comparisons and only goes through the list once.

提交回复
热议问题