How to update items on the heap? (priority queue)

When using the min / max-heap algorithm, priorities may change. One way to handle this is to delete and insert the item to update the order of the queues.

For priority queues implemented using arrays, this can be a performance bottleneck that can be avoided, especially in cases where the priority change is small.

Even if this is not a standard operation for the priority queue , it is a custom implementation that can be changed for my needs.

Are there well-known best practice methods for updating elements in min / max-heap?


Background information: I am not an expert in binary trees, I have inherited some code that has performance bottlenecks that put items in the priority queue. I made a reinsert function for the mini-heap that reorders the new item, which gives a measurable improvement (delete and insert), however this seems like a problem that others can solve in a more elegant way.

I could refer to the code if it helps, but I would not want to focus more on the implementation details, since this Q & A can probably be shared.

+4
source share
2 answers

Typical solution

, , .

, min-heap O (log n), , .

, - : "siftup" "siftdown" ( , ). , .

1:

x1 x0, x, parent(x) <= x0 < x1. x , x , x , .

2:

x1 x, x , x1 < x0 <= either_child(x). , x , x . Sibling , , .

3:

. .

Python

1,000,000 : . . . , -.

from heapq import _siftup, _siftdown, heapify
from random import random, randrange, choice

def is_minheap(arr):
    return all(arr[i] >= arr[(i-1)//2] for i in range(1, len(arr)))

n = 40
trials = 1_000_000
for _ in range(trials):

    # Create a random heap
    data = [random() for i in range(n)]
    heapify(data)

    # Randomly alter a heap element
    i = randrange(n)
    x0 = data[i]
    x1 = data[i] = choice(data)

    # Restore the heap
    if x1 > x0:                 # value is increased
        _siftup(data, i)
    elif x1 < x0:               # value is decreased
        _siftdown(data, 0, i)

    # Verify the results
    assert is_minheap(data), direction
+5

, .


.

min- , . : BubbleUp/Down.

, . :

if new_value < old_value {
    heap_bubble_up(heap, node);
} else if new_value > old_value {
    heap_bubble_down(heap, node);
}

, , .

, , +.

. code test, - // ( ).


.

, .

(, - ), .

rb- , -.

0

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


All Articles