-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeaps.py
61 lines (54 loc) · 1.44 KB
/
Heaps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
heap = []
l = None
r = None
def parent(i):
return (i-1)/2
def left(i):
return (2*i)+1
def right(i):
return (2*i)+2
def maxheapify(i,sizeofheap):
global l,r
largest = i
l = left(i)
r = right(i)
print "left and right are now ",l," and ",r," respectively"
if l<sizeofheap:
if heap[l]>heap[i]:
largest = l
print "left is the largest : ",l
else:
largest = i
print "parent is the largest : ",largest
if r<sizeofheap:
if heap[r]>heap[largest]:
largest = r
print " right is the largest : ",r
if largest != i:
print "swapping the largest of the parent, left and right to the top"
temp = heap[i]
heap[i] = heap[largest]
heap[largest] = temp
print "swap completed"
maxheapify(largest,sizeofheap)
def buildmaxheap():
global heap
heapposn = len(heap) - 1
heapsize = len(heap)
i = heapposn/2
while i>=0:
print "setting the heap for every parent node"
maxheapify(i,heapsize)
i = i - 1
while(True):
inp = raw_input("enter a number you wish to add to the heap:")
heap.append(int(inp))
choice = raw_input("Wish to add more ? (y/n)")
if choice == 'y':
continue
elif choice == 'n':
break
else:
print "Please enter either y for yes or n for a no"
buildmaxheap()
print "max heap is, ",heap