Skip to content

Commit f0f1cc9

Browse files
authored
Heap.py
This is the solution to the problem TheAlgorithms#9528
1 parent f964dcb commit f0f1cc9

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Diff for: Heap.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#Heap Sort algorithm in Python
2+
def heapify(arr, n, i):
3+
largest = i
4+
left = 2 * i + 1
5+
right = 2 * i + 2
6+
7+
if left < n and arr[left] > arr[largest]:
8+
largest = left
9+
10+
if right < n and arr[right] > arr[largest]:
11+
largest = right
12+
13+
if largest != i:
14+
arr[i], arr[largest] = arr[largest], arr[i]
15+
heapify(arr, n, largest)
16+
17+
def heap_sort(arr):
18+
n = len(arr)
19+
20+
# Build a max heap.
21+
for i in range(n // 2 - 1, -1, -1):
22+
heapify(arr, n, i)
23+
24+
# Extract elements one by one.
25+
for i in range(n - 1, 0, -1):
26+
arr[i], arr[0] = arr[0], arr[i]
27+
heapify(arr, i, 0)
28+
29+
# Example usage:
30+
arr = [12, 11, 13, 5, 6, 7]
31+
heap_sort(arr)
32+
print("Sorted array is:", arr)

0 commit comments

Comments
 (0)