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

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

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

24条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 01:30

    The following solution would take 2(N-1) comparisons:

    arr  #array with 'n' elements
    first=arr[0]
    second=-999999  #large negative no
    i=1
    while i is less than length(arr):
        if arr[i] greater than first:
            second=first
            first=arr[i]
        else:
            if arr[i] is greater than second and arr[i] less than first:
                second=arr[i]
        i=i+1
    print second
    

提交回复
热议问题