Kth largest element in a max-heap

后端 未结 4 725
清酒与你
清酒与你 2020-12-25 15:11

I\'m trying to come up with something to solve the following:

Given a max-heap represented as an array, return the kth largest element without modifyi

4条回答
  •  被撕碎了的回忆
    2020-12-25 16:03

    The max-heap can have many ways, a better case is a complete sorted array, and in other extremely case, the heap can have a total asymmetric structure.

    Here can see this: enter image description here

    In the first case, the kth lagest element is in the kth position, you can compute in O(1) with a array representation of heap. But, in generally, you'll need to check between (k, 2k) elements, and sort them (or partial sort with another heap). As far as I know, it's O(K·log(k))

    And the algorithm:

    Input:
        Integer kth <- 8
        Heap heap <- {19,18,10,17,14,9,4,16,15,13,12}
    
    BEGIN
        Heap positionHeap <- Heap with comparation: ((n0,n1)->compare(heap[n1], heap[n0]))
    
        Integer childPosition
        Integer candidatePosition <- 0
        Integer count <- 0
        positionHeap.push(candidate)
        WHILE (count < kth) DO
            candidatePosition <- positionHeap.pop();
            childPosition <- candidatePosition * 2 + 1
            IF (childPosition < size(heap)) THEN
                positionHeap.push(childPosition)
                childPosition <- childPosition + 1
                IF (childPosition < size(heap)) THEN
                    positionHeap.push(childPosition)
                END-IF
            END-IF
            count <- count + 1
        END-WHILE
        print heap[candidate]
    END-BEGIN
    

    EDITED

    I found "Optimal Algorithm of Selection in a min-heap" by Frederickson here: ftp://paranoidbits.com/ebooks/An%20Optimal%20Algorithm%20for%20Selection%20in%20a%20Min-Heap.pdf

提交回复
热议问题