Exemple #1
0
#Authors: M269 Module Team
#Date: 19/1/13

from BinaryHeap import BinaryHeap

#List from Miller and Ranum Figure 6.18.

#Example 1 - adding items one at a time
myHeap = BinaryHeap()
aList = [9, 6, 5, 2, 3]
print('Example 1 - adding items one at a time')
print('List to build heap from:', aList)
print('Heap list:', myHeap.heapList)
print('-----------------------------------------')

for k in range(len(aList)):
    myHeap.insert(aList[k])
    print('-----------------------------------------')

print('Finished: heap is', myHeap.heapList)
print()

#Example 2 - "heapifying" an existing list
myHeap2 = BinaryHeap()
bList = [9, 6, 5, 2, 3]
print('Example 2 - heapifying an existing list')
print('List to heapify:', bList)

myHeap2.buildHeap(bList)
print('Finished')
Exemple #2
0
#!/usr/bin/env python3

#Authors: M269 Module Team
#Date: 20/1/13
#Modified: 16/12/15

from BinaryHeap import BinaryHeap

#Example 1 heapsort in action
aList = [1, 9, 5, 2, 14, 4, 8, 20, 7, 42]

#First 'heapify' the list
myHeap = BinaryHeap()
myHeap.buildHeap(aList)

#Create empty list to hold the results
sortedList = []

print('The list to be sorted:', aList)
print('The heap:', myHeap.heapList)
print()

#While there are still items in the heap, pop the root and then reform the heap
while myHeap.size() > 0:
    item = myHeap.delMin()
    sortedList.append(item)

print('Finished')
print('Sorted list:', sortedList)