-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pairing Heaps.py
92 lines (69 loc) · 1.8 KB
/
Pairing 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
# coding: utf-8
# In[106]:
class PairingHeap:
def __init__(self):
self.heap = [0]
self.size = 0
self.root=min(self.heap)
def insert(self, value):
self.heap.append(value)
self.size += 1
self.BubbleUp(self.size)
def merge(self, root1, root2):
if root1 is None:
return root2
elif root2 is None:
return root1
elif root1< root2:
self.heap.append(root2)
return root1
else:
self.heap.append(root1)
return root2
def delete(self):
self.root=None
self.heap[1], self.heap[-1] = self.heap[-1], self.heap[1]
deletedValue = self.heap.pop(-1)
self.size -= 1
return deletedValue
def findMin(self):
if self.root==None:
print("Pairing Heap is empty")
else:
return self.root
def getSize(self):
print (len(self.heap))
# Two Pass Method
def BubbleUp(self, key):
if self.heap[key] > self.heap[key // 2] or key <= 1: # parent and child
return ()
else:
self.heap[key], self.heap[key // 2] = self.heap[key // 2], self.heap[key]
return self.BubbleUp(key // 2)
# Driver Code
heap = PairingHeap()
print("Pairing Heap upon Insertion:")
heap.insert(2)
heap.insert(18)
heap.insert(20)
heap.insert(1)
heap.insert(3)
heap.insert(8)
print(heap.heap)
print()
print("Getting Mininmum in pairing heap:")
print(heap.findMin())
print()
print("Merging roots in pairing heaps:")
print("Smaller root =",heap.merge(5,1))
print("Heap after merge:")
print(heap.heap)
print()
print("Pairing Heap after deleting:")
heap.delete()
heap.delete()
print(heap.heap)
print()
print("Size of Pairing Heap:")
heap.getSize()