File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ def heapify (arr , n , i ):
2+ largest = i # Initialize largest as root
3+ l = 2 * i + 1 # left = 2*i + 1
4+ r = 2 * i + 2 # right = 2*i + 2
5+
6+ # See if left child of root exists and is
7+ # greater than root
8+ if l < n and arr [i ] < arr [l ]:
9+ largest = l
10+
11+ # See if right child of root exists and is
12+ # greater than root
13+ if r < n and arr [largest ] < arr [r ]:
14+ largest = r
15+
16+ # Change root, if needed
17+ if largest != i :
18+ arr [i ],arr [largest ] = arr [largest ],arr [i ] # swap
19+
20+ # Heapify the root.
21+ heapify (arr , n , largest )
22+
23+ def heapSort (arr ):
24+ n = len (arr )
25+
26+ # Build a maxheap.
27+ for i in range (n // 2 - 1 , - 1 , - 1 ):
28+ heapify (arr , n , i )
29+
30+ # One by one extract elements
31+ for i in range (n - 1 , 0 , - 1 ):
32+ arr [i ], arr [0 ] = arr [0 ], arr [i ] # swap
33+ heapify (arr , i , 0 )
34+
35+ print ('Enter a list of numbers' )
36+ arr = list (map (int ,input ().split ()))
37+ heapSort (arr )
38+ print ('After performing heap sort' )
39+ for i in arr :
40+ print (i ,end = ' ' )
You can’t perform that action at this time.
0 commit comments