Skip to content

Commit 8a092d3

Browse files
authored
Merge pull request #59 from Aiswarya29/patch-1
Added file.py
2 parents 576c4ea + 67ed35c commit 8a092d3

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Sorting Algorithms/Heapsort.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# heapify
2+
def heapify(arr, n, i):
3+
largest = i # largest value
4+
l = 2 * i + 1 # left
5+
r = 2 * i + 2 # right
6+
# if left child exists
7+
if l < n and arr[i] < arr[l]:
8+
largest = l
9+
# if right child exits
10+
if r < n and arr[largest] < arr[r]:
11+
largest = r
12+
# root
13+
if largest != i:
14+
arr[i],arr[largest] = arr[largest],arr[i] # swap
15+
# root.
16+
heapify(arr, n, largest)
17+
# sort
18+
def heapSort(arr):
19+
n = len(arr)
20+
# maxheap
21+
for i in range(n, -1, -1):
22+
heapify(arr, n, i)
23+
# element extraction
24+
for i in range(n-1, 0, -1):
25+
arr[i], arr[0] = arr[0], arr[i] # swap
26+
heapify(arr, i, 0)
27+
# main
28+
arr = [2,5,3,8,6,5,4,7]
29+
heapSort(arr)
30+
n = len(arr)
31+
print ("Sorted array is")
32+
for i in range(n):
33+
print (arr[i],end=" ")

0 commit comments

Comments
 (0)