1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| def heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
# Check if left child exists and is greater than root
if left < n and arr[largest] < arr[left]:
largest = left
# Check if right child exists and is greater than the largest so far
if right < n and arr[largest] < arr[right]:
largest = right
# Change root if needed
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i] # Swap
heapify(arr, n, largest) # Heapify the root
def build_max_heap(arr):
n = len(arr)
# Build a max heap from the input array
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
def heap_sort(arr):
n = len(arr)
build_max_heap(arr)
# Extract elements from the heap one by one
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # Swap root with the last element
heapify(arr, i, 0) # Heapify the reduced heap
# Example usage:
arr = [12, 11, 13, 5, 6, 7]
heap_sort(arr)
print("Sorted array is:", arr) # Output: [5, 6, 7, 11, 12, 13]
|