File tree 1 file changed +54
-0
lines changed
Algorithms/Sorting Algorithms
1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ __author__ = 'Avinash'
2
+
3
+
4
+ def heapify (arr , n , i ):
5
+ """
6
+ Heapify function to build a max heap from an unsorted array.
7
+ """
8
+ largest = i # Initialize largest as root
9
+ l = 2 * i + 1 # left = 2*i + 1
10
+ r = 2 * i + 2 # right = 2*i + 2
11
+
12
+ # See if left child of root exists and is greater than root
13
+ if l < n and arr [l ] > arr [largest ]:
14
+ largest = l
15
+
16
+ # See if right child of root exists and is greater than root
17
+ if r < n and arr [r ] > arr [largest ]:
18
+ largest = r
19
+
20
+ # Change root, if needed
21
+ if largest != i :
22
+ arr [i ], arr [largest ] = arr [largest ], arr [i ] # swap
23
+
24
+ # Heapify the root.
25
+ heapify (arr , n , largest )
26
+
27
+
28
+ def heap_sort (arr ):
29
+ """
30
+ Heap sort function to sort an unsorted array in ascending order.
31
+ """
32
+ n = len (arr )
33
+
34
+ # Build a max heap.
35
+ for i in range (n // 2 - 1 , - 1 , - 1 ):
36
+ heapify (arr , n , i )
37
+
38
+ # Extract elements one by one
39
+ for i in range (n - 1 , 0 , - 1 ):
40
+ arr [i ], arr [0 ] = arr [0 ], arr [i ] # swap
41
+ heapify (arr , i , 0 )
42
+
43
+ print ('\n The sorted list: \t ' , arr )
44
+ print ('\n ' )
45
+
46
+
47
+ lst = []
48
+ size = int (input ("\n Enter size of the list: \t " ))
49
+
50
+ for input_elements in range (size ):
51
+ elements = int (input ("Enter the element: \t " ))
52
+ lst .append (elements )
53
+
54
+ heap_sort (lst )
You can’t perform that action at this time.
0 commit comments