Videos
Does heapify take an unordered array and convert it into a heap in O(n) time ? I think this is specific to Python and there is some fancy math on why.
But in other languages like JavaScript for example, is n log n, this makes sense to me since you are adding n elements and each takes log n time. And how you have a sorted heap.
According to the example from the documentation, you can use tuples, and it will sort by the first element of the tuple:
>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')
So if you don't want to (or can't?) do a __cmp__ method, you can manually extract your sorting key at push time.
Note that if the first elements in a pair of tuples are equal, further elements will be compared. If this is not what you want, you need to ensure that each first element is unique.
heapq sorts objects the same way list.sort does, so just define a method __cmp__() within your class definition, which will compare itself to another instance of the same class:
def __cmp__(self, other):
return cmp(self.intAttribute, other.intAttribute)
Works in Python 2.x.
In 3.x use:
def __lt__(self, other):
return self.intAttribute < other.intAttribute
In Python 2.X and 3.x, heaps are supported through an importable library, heapq. It supplies numerous functions to work with the heap data structure modelled in a Python list. Example:
>>> from heapq import heappush, heappop
>>> heap = []
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> for item in data:
heappush(heap, item)
>>> ordered = []
>>> while heap:
ordered.append(heappop(heap))
>>> ordered
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> data.sort()
>>> data == ordered
True
You can find out more about Heap functions: heappush, heappop, heappushpop, heapify, heapreplace in heap python docs.
Here's another variation based on Sedgewick
The heap is represented internally in an array where if a node is at k, it's children are at 2*k and 2*k + 1. The first element of the array is not used, to make the math more convenient.
To add a new element to the heap, you append it to the end of the array and then call swim repeatedly until the new element finds its place in the heap.
To delete the root, you swap it with the last element in the array, delete it and then call sink until the swapped element finds its place.
swim(k):
while k > 1 and less(k/2, k):
exch(k, k/2)
k = k/2
sink(k):
while 2*k <= N:
j = 2*k
if j < N and less(j, j+1):
j++
if not less(k, j):
break
exch(k, j)
k = j
Here's a visualization of heap insert, inserting the first 15 letters of the alphabet: [a-o]
