1
+ class MaxHeap :
2
+ def __init__ (self ):
3
+ self .items = [0 ] * 100
4
+ self .size = 0
5
+
6
+ def swap (self , a , b ):
7
+ self .items [a ], self .items [b ] = self .items [b ], self .items [a ]
8
+
9
+ def heapify_up (self , index ):
10
+ while index > 0 and self .items [(index - 1 ) // 2 ] < self .items [index ]:
11
+ self .swap ((index - 1 ) // 2 , index )
12
+ index = (index - 1 ) // 2
13
+
14
+ def heapify_down (self , index ):
15
+ largest = index
16
+ left_child = 2 * index + 1
17
+ right_child = 2 * index + 2
18
+
19
+ if left_child < self .size and self .items [left_child ] > self .items [largest ]:
20
+ largest = left_child
21
+ if right_child < self .size and self .items [right_child ] > self .items [largest ]:
22
+ largest = right_child
23
+
24
+ if largest != index :
25
+ self .swap (index , largest )
26
+ self .heapify_down (largest )
27
+
28
+ def insert (self , value ):
29
+ if self .size >= 100 :
30
+ print ("Heap is full. Cannot insert." )
31
+ return
32
+ self .items [self .size ] = value
33
+ self .size += 1
34
+ self .heapify_up (self .size - 1 )
35
+
36
+ def delete_max (self ):
37
+ if self .size == 0 :
38
+ print ("Heap is empty. Cannot delete." )
39
+ return - 1
40
+ deleted_item = self .items [0 ]
41
+ self .items [0 ] = self .items [self .size - 1 ]
42
+ self .size -= 1
43
+ self .heapify_down (0 )
44
+ return deleted_item
45
+
46
+ def heap_sort (arr ):
47
+ heap = MaxHeap ()
48
+
49
+ # Inserting elements into the max heap
50
+ for i in range (len (arr )):
51
+ heap .insert (arr [i ])
52
+
53
+ # Deleting elements from the max heap and storing them in sorted order
54
+ for i in range (len (arr ) - 1 , - 1 , - 1 ):
55
+ arr [i ] = heap .delete_max ()
56
+
57
+ return arr
58
+
59
+ arr = [4 , 10 , 3 , 5 , 1 ]
60
+ arr = heap_sort (arr )
61
+
62
+ # Displaying sorted array
63
+ print ("Sorted array:" , arr )
0 commit comments