1
- """
1
+ '''
2
2
This is a pure python implementation of the heap sort algorithm.
3
3
4
4
For doctests run following command:
8
8
9
9
For manual testing run:
10
10
python 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
31
32
:param collection: some mutable ordered collection with heterogeneous
32
33
comparable items inside
33
34
:return: the same collection ordered by ascending
@@ -41,16 +42,15 @@ def heap_sort(unsorted):
41
42
42
43
>>> heap_sort([-2, -5, -45])
43
44
[-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 )
51
52
return unsorted
52
53
53
-
54
54
if __name__ == '__main__' :
55
55
import sys
56
56
if sys .version_info .major < 3 :
@@ -60,4 +60,4 @@ def heap_sort(unsorted):
60
60
61
61
user_input = input_function ('Enter numbers separated by a comma:\n ' )
62
62
unsorted = [int (item ) for item in user_input .split (',' )]
63
- print (heap_sort (unsorted ))
63
+ print (heap_sort (unsorted ))
0 commit comments