Skip to content

Commit 96c5b77

Browse files
Added reverse_selection.py
1 parent fcf82a1 commit 96c5b77

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

sorts/reverse_selection.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
A pure Python implementation of the Reverse Selection Sort algorithm
3+
4+
This algorithm progressively sorts the array by reversing subarrays
5+
6+
For doctests run following command:
7+
python3 -m doctest -v reverse_selection_sort.py
8+
9+
For manual testing run:
10+
python3 reverse_selection_sort.py
11+
"""
12+
13+
def reverse_subarray(arr: list, start: int, end: int) -> None:
14+
"""
15+
Reverse a subarray in-place.
16+
17+
:param arr: the array containing the subarray to be reversed
18+
:param start: the starting index of the subarray
19+
:param end: the ending index of the subarray
20+
"""
21+
while start < end:
22+
arr[start], arr[end] = arr[end], arr[start]
23+
start += 1
24+
end -= 1
25+
26+
def reverse_selection_sort(collection: list) -> list:
27+
"""
28+
A pure implementation of reverse selection sort algorithm in Python
29+
30+
:param collection: some mutable ordered collection with heterogeneous
31+
comparable items inside
32+
:return: the same collection sorted in ascending order
33+
34+
Examples:
35+
>>> reverse_selection_sort([1, 9, 5, 21, 17, 6])
36+
[1, 5, 6, 9, 17, 21]
37+
38+
>>> reverse_selection_sort([])
39+
[]
40+
41+
>>> reverse_selection_sort([-3, -17, -48])
42+
[-48, -17, -3]
43+
"""
44+
n = len(collection)
45+
for i in range(n - 1):
46+
# Find the minimum element in the unsorted portion
47+
min_idx = i
48+
for j in range(i + 1, n):
49+
if collection[j] < collection[min_idx]:
50+
min_idx = j
51+
52+
# If the minimum is not at the start of the unsorted portion,
53+
# reverse the subarray to bring it to the front
54+
if min_idx != i:
55+
reverse_subarray(collection, i, min_idx)
56+
57+
return collection
58+
59+
if __name__ == "__main__":
60+
user_input = input("Enter numbers separated by a comma:\n").strip()
61+
unsorted = [int(item) for item in user_input.split(",")]
62+
print(reverse_selection_sort(unsorted))

0 commit comments

Comments
 (0)