Skip to content

Commit ace2863

Browse files
Merge pull request akshitagit#138 from N00rAhmed/SecondBranch
added HeapSort to Sorts folder in Python Programming Language
2 parents ecbc1ce + 78f91ca commit ace2863

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Sorts/HeapSort.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Python program for implementation of heap Sort
2+
3+
# To heapify subtree rooted at index i.
4+
# n is size of heap
5+
6+
7+
def heapify(arr, N, i):
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
13+
# greater than root
14+
if l < N and arr[largest] < arr[l]:
15+
largest = l
16+
17+
# See if right child of root exists and is
18+
# greater than root
19+
if r < N and arr[largest] < arr[r]:
20+
largest = r
21+
22+
# Change root, if needed
23+
if largest != i:
24+
arr[i], arr[largest] = arr[largest], arr[i] # swap
25+
26+
# Heapify the root.
27+
heapify(arr, N, largest)
28+
29+
# The main function to sort an array of given size
30+
31+
32+
def heapSort(arr):
33+
N = len(arr)
34+
35+
# Build a maxheap.
36+
for i in range(N//2 - 1, -1, -1):
37+
heapify(arr, N, i)
38+
39+
# One by one extract elements
40+
for i in range(N-1, 0, -1):
41+
arr[i], arr[0] = arr[0], arr[i] # swap
42+
heapify(arr, i, 0)
43+
44+
45+
# Driver's code
46+
if __name__ == '__main__':
47+
arr = [12, 11, 13, 5, 6, 7]
48+
49+
# Function call
50+
heapSort(arr)
51+
N = len(arr)
52+
53+
print("Sorted array is")
54+
for i in range(N):
55+
print("%d" % arr[i], end=" ")
56+
57+
# Provided by Noor Ahmed

0 commit comments

Comments
 (0)