Skip to content

Commit 37d750d

Browse files
committed
Heap sort Algorithm in Python
1 parent 8f851c6 commit 37d750d

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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('\nThe sorted list: \t', arr)
44+
print('\n')
45+
46+
47+
lst = []
48+
size = int(input("\nEnter 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)

0 commit comments

Comments
 (0)