This repository was archived by the owner on Nov 4, 2024. It is now read-only.
File tree 1 file changed +90
-0
lines changed 1 file changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # author: bt3gl
4
+
5
+ class MinHeap :
6
+
7
+ def __init__ (self , size ):
8
+
9
+ self .heapsize = size
10
+ self .minheap = [0 ] * (size + 1 )
11
+ self .realsize = 0
12
+
13
+ def add (self , element ):
14
+
15
+ if self .realsize + 1 > self .heapsize :
16
+ print ("Too many elements!" )
17
+ return False
18
+
19
+ self .realsize += 1
20
+ self .minheap [self .realsize ] = element
21
+
22
+ index = self .realsize
23
+ parent = index // 2
24
+
25
+ while self .minheap [index ] < self .minheap [parent ] and index > 1 :
26
+
27
+ self .minheap [parent ], self .minheap [index ] = self .minheap [index ], self .minheap [parent ]
28
+ index = parent
29
+ parent = index // 2
30
+
31
+ def peek (self ):
32
+
33
+ return self .minheap [1 ]
34
+
35
+ def pop (self ):
36
+
37
+ if self .realsize < 1 :
38
+ print ("Heap is empty." )
39
+ return False
40
+
41
+ else :
42
+ remove_element = self .minheap [1 ]
43
+ self .minheap [1 ] = self .minheap [self .realsize ]
44
+ self .realsize -= 1
45
+ index = 1
46
+
47
+ while index <= self .realsize // 2 :
48
+
49
+ left_children = index * 2
50
+ right_children = (index * 2 ) + 1
51
+
52
+ if self .minheap [index ] > self .minheap [left_children ] or \
53
+ self .minheap [index ] > self .minheap [right_children ]:
54
+
55
+ if self .minheap [left_children ] < self .minheap [right_children ]:
56
+
57
+ self .minheap [left_children ], self .minheap [index ] = self .minheap [index ], self .minheap [left_children ]
58
+ index = left_children
59
+
60
+ else :
61
+
62
+ self .minheap [right_children ], self .minheap [index ] = self .minheap [index ], self .minheap [right_children ]
63
+ index = right_children
64
+ else :
65
+ break
66
+
67
+ return remove_element
68
+
69
+ def size (self ):
70
+ return self .realsize
71
+
72
+ def __str__ (self ):
73
+ return str (self .minheap [1 : self .realsize + 1 ])
74
+
75
+
76
+ if __name__ == "__main__" :
77
+ # Test cases
78
+ h = MinHeap (5 )
79
+ h .add (3 )
80
+ h .add (1 )
81
+ h .add (2 )
82
+
83
+ print (h )
84
+ print (h .peek ())
85
+ print (h .pop ())
86
+ print (h .pop ())
87
+ print (h .pop ())
88
+ h .add (4 )
89
+ h .add (5 )
90
+ print (h )
You can’t perform that action at this time.
0 commit comments