-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap_sort.py
39 lines (30 loc) · 1.07 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
""" created by Sarvesh kumar sharma """
'''implementation of the Heap sort algorithm in Python'''
# heap sort
def heap_sort(list2):
first = 0
last = len(list2) - 1
create_heap(list2, first, last)
for i in range(last, first, -1):
list2[i], list2[first] = list2[first], list2[i] # swap
establish_heap_property(list2, first, i - 1)
# create heap (used by heap_sort)
def create_heap(list2, first, last):
i = last / 2
while i >= first:
establish_heap_property(list2, i, last)
i -= 1
# establish heap property (used by create_heap)
def establish_heap_property(list2, first, last):
while 2 * first + 1 <= last:
k = 2 * first + 1
if k < last and list2[k] < list2[k + 1]:
k += 1
if list2[first] >= list2[k]:
break
list2[first], list2[k] = list2[k], list2[first] # swap
first = k
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(heap_sort(unsorted))