DEV Community

Akhil
Akhil

Posted on

Functions in Heap

Functions in Heap :

The following functions are:

heapq.heappush(heap, item)

Move the value object onto the heap, retaining the invariant heap.

heapq.heappushpop(heap, item)

On the heap, push the object, pop and return the smallest item from the heap.

heapq.heapify(x)

Transform list x into a heap in linear time, in-place.

heapq.heapreplace(heap, item)

Pop the smallest item from the heap and return it and push the new item as well.The heap size doesn’t change. If the heap is empty, IndexError is raised.

This one-step operation is more successful than heappop(), followed by heappush(), and when using a fixed-size heap, it can be more suitable.

An element from the heap is always returned by the pop/push combination and replaced with an object.

The returned value may be greater than the added object.If that isn’t desired, instead, consider using heappushpop().The smaller of the two values is returned by its push/pop combination, leaving on the heap the larger value.

heapq.merge(*iterables, key=None, reverse=False)

Combine different sorted inputs into one single sorted output(for example, merge timestamped entries from multiple log files).Returns an iterator over the values sorted.

Code :
def heapsort(iterable):
h = []
for value in iterable:
heappush(h, value)
return [heappop(h) for i in range(len(h))]

heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Top comments (0)