-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap_sort.py
64 lines (46 loc) · 1.81 KB
/
heap_sort.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import time
compare_count = 0
swap_count = 0
def heapify(array, current_index, heap_size, sort_order):
global compare_count
global swap_count
largest_element = current_index
left_child = 2 * current_index + 1
right_child = 2 * current_index + 2
def compare(a, b):
if a >= b:
return 1
else:
return -1
if left_child < heap_size and compare(array[left_child], array[largest_element]) != compare(sort_order, "desc"):
largest_element = left_child
compare_count += 4
if right_child < heap_size and compare(array[right_child], array[largest_element]) != compare(sort_order, "desc"):
largest_element = right_child
compare_count += 4
if largest_element != current_index:
array[current_index], array[largest_element] = array[largest_element], array[current_index]
compare_count += 1
swap_count += 1
heapify(array, largest_element, heap_size, sort_order)
def heap_sort(array, sort_order):
global swap_count
array_length = len(array)
for i in range(array_length // 2, -1, -1):
heapify(array, i, array_length, sort_order)
for i in range(array_length - 1, 0, -1):
array[i], array[0] = array[0], array[i]
heapify(array, 0, i, sort_order)
swap_count += 1
return array
if __name__ == "__main__":
sort_order = str(input("Enter sort order (asc or desc): "))
array = [int(item) for item in input("Enter initial array: ").split(",")]
start_time = time.perf_counter()
heap_sort(array, sort_order)
end_time = time.perf_counter()
execution_time = (end_time - start_time) * 1000
print(f"Execution time: {execution_time} ms")
print(f"Comparisons: {compare_count}")
print(f"Swaps: {swap_count}")
print("Heap sort:", heap_sort(array, sort_order))