import random def above(i): """ Return index of heap slot above one """ # Here's what it looks like: # 0 # 1 2 # 3 4 5 6 # so above(3) = above(4) = 1 # if i == 0: return 0 else: return (i-1)/2 class Heap(object): """ minimum heap implementation """ # TODO: add error checking so that max_size isn't exceeded. def __init__(self, max_size = 100): self.max_size = max_size self.data = [None]*max_size self.size = 0 def peek(self): """ Return smallest value in heap """ return self.data[0] def swap(self, i, j): """ In place exchange two values with given indices """ temp = self.data[i] self.data[i] = self.data[j] self.data[j] = temp def push(self, value): """ put a new value into the heap; adjust accordingly""" self.data[self.size] = value self.size += 1 index = self.size - 1 # need to bubble this up while self.data[index] < self.data[above(index)]: self.swap(index, above(index)) index = above(index) def pop(self): # TODO: something similar ... return 0 def main(): h = Heap() # make an empty one print "Making a heap with 10 numbers in it." for i in random.sample(range(100), 10): h.push(i) # add a number to the heap value = h.peek() # get smallest, no removal print "The smallest value is " + str(value) print "The 5 smallest are: ", for i in range(5): value = h.pop() # remove smallest number print " " + str(value), print main()