Find the n largest elements from an array

I have an array

A[4]={4,5,9,1}

I need it to give the first 3 top elements like 9,5,4

I know how to find the maximum element, but how to find the 2nd and 3rd maximum?

ie if

max=A[0]
for(i=1;i<4;i++)
{
  if (A[i]>max)
  {
    max=A[i];
    location=i+1;
  }
}

actual sorting is not suitable for my application because

the position number is also important to me, i.e. I need to know in what positions the first maximum 3 occurs, here it is in the 0th, 1st and 2nd positions ... so I think about the logic

that after getting the maximum value, if I could put 0 in this place and could apply the same steps for this new array, that is {4,5,0,1}

But I'm a little confused how to put my logic in code

+4
source share
4 answers

, Python. :

def nlargest(n, iterable):
    """Find the n largest elements in a dataset.

    Equivalent to:  sorted(iterable, reverse=True)[:n]
    """
    if n < 0:
        return []
    it = iter(iterable)
    result = list(islice(it, n))
    if not result:
        return result
    heapify(result)
    for elem in it:
        heappushpop(result, elem)
    result.sort(reverse=True)
    return result

:

- ( , ) (. ).

+4

, O (n), .. O (n) O (n) , O (n)

+2

, , . - heapsort quicksort .

, 0, 1,...., , n- n-1

0

,
1. n B[n];
2. B[n]
3. A[n...m] check,
  A[k]>B[0]  , A[k] n , ,   A[k] B[n] B[n], B[n] n .
4. A[m].
B[n] n .

0

Source: https://habr.com/ru/post/1533484/


All Articles