-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtm3_heapsort.py
45 lines (32 loc) · 1.09 KB
/
tm3_heapsort.py
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
38
39
40
41
42
43
44
45
def heapify(arr, n, i):
largest = i # Initialize largest as root
left = 2 * i + 1 # left = 2*i + 1
right = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is greater than root
if left < n and arr[i] < arr[left]:
largest = left
# See if right child of root exists and is greater than root
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 the root.
heapify(arr, n, largest)
def heap_sort(arr):
n = len(arr)
# Build a maxheap.
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
if __name__ == "__main__":
# Get user input
arr = list(map(int, input("Please enter the numbers separated by space: ").split()))
print("Array before sorting:")
print(arr)
heap_sort(arr)
print("Array after sorting:")
print(arr)