1
1
"""
2
- This is a pure Python implementation of the heap sort algorithm.
3
-
4
- For doctests run following command:
5
- python -m doctest -v heap_sort.py
6
- or
7
- python3 -m doctest -v heap_sort.py
8
-
9
- For manual testing run:
10
- python heap_sort.py
2
+ A pure Python implementation of the heap sort algorithm.
11
3
"""
12
4
13
5
14
- def heapify (unsorted , index , heap_size ):
6
+ def heapify (unsorted : list [int ], index : int , heap_size : int ) -> None :
7
+ """
8
+ :param unsorted: unsorted list containing integers numbers
9
+ :param index: index
10
+ :param heap_size: size of the heap
11
+ :return: None
12
+ >>> unsorted = [1, 4, 3, 5, 2]
13
+ >>> heapify(unsorted, 0, len(unsorted))
14
+ >>> unsorted
15
+ [4, 5, 3, 1, 2]
16
+ >>> heapify(unsorted, 0, len(unsorted))
17
+ >>> unsorted
18
+ [5, 4, 3, 1, 2]
19
+ """
15
20
largest = index
16
21
left_index = 2 * index + 1
17
22
right_index = 2 * index + 2
@@ -22,26 +27,26 @@ def heapify(unsorted, index, heap_size):
22
27
largest = right_index
23
28
24
29
if largest != index :
25
- unsorted [largest ], unsorted [index ] = unsorted [index ], unsorted [largest ]
30
+ unsorted [largest ], unsorted [index ] = ( unsorted [index ], unsorted [largest ])
26
31
heapify (unsorted , largest , heap_size )
27
32
28
33
29
- def heap_sort (unsorted ) :
34
+ def heap_sort (unsorted : list [ int ]) -> list [ int ] :
30
35
"""
31
- Pure implementation of the heap sort algorithm in Python
32
- :param collection: some mutable ordered collection with heterogeneous
33
- comparable items inside
36
+ A pure Python implementation of the heap sort algorithm
37
+
38
+ :param collection: a mutable ordered collection of heterogeneous comparable items
34
39
:return: the same collection ordered by ascending
35
40
36
41
Examples:
37
42
>>> heap_sort([0, 5, 3, 2, 2])
38
43
[0, 2, 2, 3, 5]
39
-
40
44
>>> heap_sort([])
41
45
[]
42
-
43
46
>>> heap_sort([-2, -5, -45])
44
47
[-45, -5, -2]
48
+ >>> heap_sort([3, 7, 9, 28, 123, -5, 8, -30, -200, 0, 4])
49
+ [-200, -30, -5, 0, 3, 4, 7, 8, 9, 28, 123]
45
50
"""
46
51
n = len (unsorted )
47
52
for i in range (n // 2 - 1 , - 1 , - 1 ):
@@ -53,6 +58,10 @@ def heap_sort(unsorted):
53
58
54
59
55
60
if __name__ == "__main__" :
61
+ import doctest
62
+
63
+ doctest .testmod ()
56
64
user_input = input ("Enter numbers separated by a comma:\n " ).strip ()
57
- unsorted = [int (item ) for item in user_input .split ("," )]
58
- print (heap_sort (unsorted ))
65
+ if user_input :
66
+ unsorted = [int (item ) for item in user_input .split ("," )]
67
+ print (f"{ heap_sort (unsorted ) = } " )
0 commit comments