Example #1
0
class PQueue:
    """This is a priority queue implementation"""
    def __init__(self,A):
        self._heap = Heap(A)

    def __str__(self):
        return str(self._heap.heap[1:])

    def peekMax(self):
        return self._heap[1]
    
    def extractMax(self):
        if self._heap.heapsize < 1:
            raise Exception("Heap underflow!")
        _max = self._heap[1]
        self._heap[1] = self._heap[self._heap.heapsize]
        self._heap.heapsize -= 1
        self._heap.maxHeapify(1)
        return _max
    
    def increaseKey(self,i,key):
        if key < self._heap[i]:
            raise Exception("New key is smaller than current key")
        self._heap[i] = key
        while i > 1 and self._heap[self._heap.Parent(i)] < self._heap[i]:
            self._heap[i],self._heap[self._heap.Parent(i)] = self._heap[self._heap.Parent(i)],self._heap[i]
            i = self._heap.Parent(i)
    
    def insert(self,key):
        self._heap.append(float("-inf"))
        self.increaseKey(self._heap.heapsize,key);
Example #2
0
 def heapSort(self,A):
     from Heap import Heap
     h = Heap(A)
     i = len(A)
     while i >= 2:
         j = h.heap[1]  
         h.heap [1] = h.heap[i]
         h.heap [i] = j
         h.heapsize = h.heapsize - 1
         h.maxHeapify(1)
         i = i-1
     return h.heap[1:len(h.heap)]