Skip to content

Commit 474700c

Browse files
authored
Merge pull request ephremdeme#65 from shaswatsingh19/master
heap sort
2 parents 7f3d226 + 3dfc043 commit 474700c

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

sorting-algorithms/Heap Sort.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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 =' ')

0 commit comments

Comments
 (0)