File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ # To heapify
2
+ def heapify (array , num , x ):
3
+ # Find the largest among root, left child and right child
4
+ max = x
5
+ left = 2 * x + 1
6
+ right = 2 * x + 2
7
+
8
+ if left < num and array [x ] < array [left ]:
9
+ max = left
10
+
11
+ if right < num and array [max ] < array [right ]:
12
+ max = right
13
+
14
+ # If root is not largest, swap and continue heapifying
15
+ if max != x :
16
+ array [x ], array [max ] = array [max ], array [x ]
17
+ heapify (array , num , max )
18
+
19
+
20
+ # To insert an element
21
+ def insert (nums , next ):
22
+ s = len (nums )
23
+ if s == 0 :
24
+ nums .append (next )
25
+ else :
26
+ nums .append (next )
27
+ for i in range ((s // 2 ) - 1 , - 1 , - 1 ):
28
+ heapify (nums , s , i )
29
+
30
+
31
+ # To delete an element
32
+ def delete (nums , n ):
33
+ s = len (nums )
34
+ i = 0
35
+ for i in range (0 , s ):
36
+ if n == nums [i ]:
37
+ break
38
+
39
+ nums [i ], nums [s - 1 ] = nums [s - 1 ], nums [i ]
40
+
41
+ nums .remove (s - 1 )
42
+
43
+ for i in range ((len (nums ) // 2 ) - 1 , - 1 , - 1 ):
44
+ heapify (nums , len (nums ), i )
45
+
46
+
47
+ array = []
48
+
49
+ insert (array , 1 )
50
+ insert (array , 4 )
51
+ insert (array , 2 )
52
+ insert (array , 7 )
53
+ insert (array , 8 )
54
+ insert (array , 5 )
55
+ insert (array , 6 )
56
+
57
+ print ("Max-Heap array: " + str (array ))
58
+
59
+ delete (array , 6 )
60
+ print ("After deletion: " + str (array ))
You can’t perform that action at this time.
0 commit comments