10
10
python3 reverse_selection_sort.py
11
11
"""
12
12
13
-
14
13
def reverse_subarray (arr : list , start : int , end : int ) -> None :
15
14
"""
16
15
Reverse a subarray in-place.
17
-
16
+
18
17
:param arr: the array containing the subarray to be reversed
19
18
:param start: the starting index of the subarray
20
19
:param end: the ending index of the subarray
20
+
21
+ Examples:
22
+ >>> lst = [1, 2, 3, 4, 5]
23
+ >>> reverse_subarray(lst, 1, 3)
24
+ >>> lst
25
+ [1, 4, 3, 2, 5]
26
+
27
+ >>> lst = [1]
28
+ >>> reverse_subarray(lst, 0, 0)
29
+ >>> lst
30
+ [1]
31
+
32
+ >>> lst = [1, 2]
33
+ >>> reverse_subarray(lst, 0, 1)
34
+ >>> lst
35
+ [2, 1]
21
36
"""
22
37
while start < end :
23
38
arr [start ], arr [end ] = arr [end ], arr [start ]
24
39
start += 1
25
40
end -= 1
26
41
27
-
28
42
def reverse_selection_sort (collection : list ) -> list :
29
43
"""
30
44
A pure implementation of reverse selection sort algorithm in Python
@@ -42,6 +56,12 @@ def reverse_selection_sort(collection: list) -> list:
42
56
43
57
>>> reverse_selection_sort([-3, -17, -48])
44
58
[-48, -17, -3]
59
+
60
+ >>> reverse_selection_sort([1, 1, 1, 1])
61
+ [1, 1, 1, 1]
62
+
63
+ >>> reverse_selection_sort([5, 4, 3, 2, 1])
64
+ [1, 2, 3, 4, 5]
45
65
"""
46
66
n = len (collection )
47
67
for i in range (n - 1 ):
@@ -50,15 +70,14 @@ def reverse_selection_sort(collection: list) -> list:
50
70
for j in range (i + 1 , n ):
51
71
if collection [j ] < collection [min_idx ]:
52
72
min_idx = j
53
-
73
+
54
74
# If the minimum is not at the start of the unsorted portion,
55
75
# reverse the subarray to bring it to the front
56
76
if min_idx != i :
57
77
reverse_subarray (collection , i , min_idx )
58
-
78
+
59
79
return collection
60
80
61
-
62
81
if __name__ == "__main__" :
63
82
user_input = input ("Enter numbers separated by a comma:\n " ).strip ()
64
83
unsorted = [int (item ) for item in user_input .split ("," )]
0 commit comments