11"""
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.
113"""
124
135
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+ """
1520 largest = index
1621 left_index = 2 * index + 1
1722 right_index = 2 * index + 2
@@ -22,26 +27,26 @@ def heapify(unsorted, index, heap_size):
2227 largest = right_index
2328
2429 if largest != index :
25- unsorted [largest ], unsorted [index ] = unsorted [index ], unsorted [largest ]
30+ unsorted [largest ], unsorted [index ] = ( unsorted [index ], unsorted [largest ])
2631 heapify (unsorted , largest , heap_size )
2732
2833
29- def heap_sort (unsorted ) :
34+ def heap_sort (unsorted : list [ int ]) -> list [ int ] :
3035 """
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
3439 :return: the same collection ordered by ascending
3540
3641 Examples:
3742 >>> heap_sort([0, 5, 3, 2, 2])
3843 [0, 2, 2, 3, 5]
39-
4044 >>> heap_sort([])
4145 []
42-
4346 >>> heap_sort([-2, -5, -45])
4447 [-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]
4550 """
4651 n = len (unsorted )
4752 for i in range (n // 2 - 1 , - 1 , - 1 ):
@@ -53,6 +58,10 @@ def heap_sort(unsorted):
5358
5459
5560if __name__ == "__main__" :
61+ import doctest
62+
63+ doctest .testmod ()
5664 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