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

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

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

24条回答
  •  醉酒成梦
    2020-11-28 01:27

    Assuming space is irrelevant, this is the smallest I could get it. It requires 2*n comparisons in worst case, and n comparisons in best case:

    arr = [ 0, 12, 13, 4, 5, 32, 8 ]
    max = [ -1, -1 ]
    
    for i in range(len(arr)):
         if( arr[i] > max[0] ):
            max.insert(0,arr[i])
         elif( arr[i] > max[1] ):
            max.insert(1,arr[i])
    
    print max[1]
    

提交回复
热议问题