1- """
1+ '''
22This is a pure python implementation of the heap sort algorithm.
33
44For doctests run following command:
88
99For manual testing run:
1010python insertion_sort.py
11- """
12- from __future__ import print_function
13-
14-
15- def heapify (unsorted ,index ,heap_size ):
16- largest = index
17- left_index = 2 * index + 1
18- right_index = 2 * index + 2
19- if left_index < heap_size and unsorted [left_index ] > unsorted [largest ]:
20- largest = left_index
21-
22- if right_index < heap_size and unsorted [right_index ] > unsorted [largest ]:
23- largest = right_index
24-
25- if largest != index :
26- unsorted [largest ],unsorted [index ] = unsorted [index ],unsorted [largest ]
27- heapify (unsorted ,largest ,heap_size )
28-
29- def heap_sort (unsorted ):
30- """Pure implementation of the heap sort algorithm in Python
11+ '''
12+
13+ from __future__ import print_function
14+
15+ def heapify (unsorted , index , heap_size ):
16+ largest = index
17+ left_index = 2 * index + 1
18+ right_index = 2 * index + 2
19+ if left_index < heap_size and unsorted [left_index ] > unsorted [largest ]:
20+ largest = left_index
21+
22+ if right_index < heap_size and unsorted [right_index ] > unsorted [largest ]:
23+ largest = right_index
24+
25+ if largest != index :
26+ unsorted [largest ], unsorted [index ] = unsorted [index ], unsorted [largest ]
27+ heapify (unsorted , largest , heap_size )
28+
29+ def heap_sort (unsorted ):
30+ '''
31+ Pure implementation of the heap sort algorithm in Python
3132 :param collection: some mutable ordered collection with heterogeneous
3233 comparable items inside
3334 :return: the same collection ordered by ascending
@@ -41,16 +42,15 @@ def heap_sort(unsorted):
4142
4243 >>> heap_sort([-2, -5, -45])
4344 [-45, -5, -2]
44- """
45- n = len (unsorted )
46- for i in range (n / 2 - 1 , - 1 , - 1 ):
47- heapify (unsorted ,i , n )
48- for i in range (n - 1 , - 1 , - 1 ):
49- unsorted [0 ], unsorted [i ] = unsorted [i ], unsorted [0 ]
50- heapify (unsorted ,0 , i )
45+ '''
46+ n = len (unsorted )
47+ for i in range (n // 2 - 1 , - 1 , - 1 ):
48+ heapify (unsorted , i , n )
49+ for i in range (n - 1 , - 1 , - 1 ):
50+ unsorted [0 ], unsorted [i ] = unsorted [i ], unsorted [0 ]
51+ heapify (unsorted , 0 , i )
5152 return unsorted
5253
53-
5454if __name__ == '__main__' :
5555 import sys
5656 if sys .version_info .major < 3 :
@@ -60,4 +60,4 @@ def heap_sort(unsorted):
6060
6161 user_input = input_function ('Enter numbers separated by a comma:\n ' )
6262 unsorted = [int (item ) for item in user_input .split (',' )]
63- print (heap_sort (unsorted ))
63+ print (heap_sort (unsorted ))
0 commit comments