Skip to content

Commit 7c59ca3

Browse files
Updated reverse_selection.py
1 parent 608e6ed commit 7c59ca3

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

sorts/reverse_selection.py

+25-6
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,35 @@
1010
python3 reverse_selection_sort.py
1111
"""
1212

13-
1413
def reverse_subarray(arr: list, start: int, end: int) -> None:
1514
"""
1615
Reverse a subarray in-place.
17-
16+
1817
:param arr: the array containing the subarray to be reversed
1918
:param start: the starting index of the subarray
2019
: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]
2136
"""
2237
while start < end:
2338
arr[start], arr[end] = arr[end], arr[start]
2439
start += 1
2540
end -= 1
2641

27-
2842
def reverse_selection_sort(collection: list) -> list:
2943
"""
3044
A pure implementation of reverse selection sort algorithm in Python
@@ -42,6 +56,12 @@ def reverse_selection_sort(collection: list) -> list:
4256
4357
>>> reverse_selection_sort([-3, -17, -48])
4458
[-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]
4565
"""
4666
n = len(collection)
4767
for i in range(n - 1):
@@ -50,15 +70,14 @@ def reverse_selection_sort(collection: list) -> list:
5070
for j in range(i + 1, n):
5171
if collection[j] < collection[min_idx]:
5272
min_idx = j
53-
73+
5474
# If the minimum is not at the start of the unsorted portion,
5575
# reverse the subarray to bring it to the front
5676
if min_idx != i:
5777
reverse_subarray(collection, i, min_idx)
58-
78+
5979
return collection
6080

61-
6281
if __name__ == "__main__":
6382
user_input = input("Enter numbers separated by a comma:\n").strip()
6483
unsorted = [int(item) for item in user_input.split(",")]

0 commit comments

Comments
 (0)