Skip to content

Commit 1779549

Browse files
committed
Added Reverse Selection Sort Algorithm
1 parent e9e7c96 commit 1779549

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

sorts/reverse_selection_sort.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
A Python implementation of the Reverse Selection Sort algorithm.
3+
4+
This algorithm progressively sorts the array by finding the largest
5+
element and reversing subarrays to place it at the correct position.
6+
7+
Inspired by the Pancake Sorting algorithm.
8+
For more information, see: https://en.wikipedia.org/wiki/Pancake_sorting
9+
10+
Examples:
11+
>>> reverse_selection_sort([45, 23, 11, 89, 54, 1, 3, 36])
12+
[89, 54, 45, 36, 23, 11, 3, 1]
13+
>>> reverse_selection_sort([0, -89, 32, 5, 46, 8, 11])
14+
[46, 32, 11, 8, 5, 0, -89]
15+
>>> reverse_selection_sort([34, -2, -1, 98, -42])
16+
[98, 34, -1, -2, -42]
17+
"""
18+
19+
def reverse_selection_sort(collection: list) -> list:
20+
"""
21+
A pure implementation of reverse selection sort algorithm in Python.
22+
:param collection: some mutable ordered collection with heterogeneous
23+
comparable items inside
24+
:return: the same collection sorted in descending order
25+
"""
26+
n = len(collection)
27+
for i in range(n):
28+
# Find the maximum element in the unsorted portion
29+
max_idx = i
30+
for j in range(i + 1, n):
31+
if collection[j] > collection[max_idx]:
32+
max_idx = j
33+
34+
# Reverse the subarray from the current position to the end
35+
collection[i:max_idx+1] = reversed(collection[i:max_idx+1])
36+
37+
return collection
38+
39+
40+
if __name__ == "__main__":
41+
user_input = input("Enter numbers separated by a comma:\n").strip()
42+
unsorted = [int(item) for item in user_input.split(",")]
43+
print(reverse_selection_sort(unsorted))

0 commit comments

Comments
 (0)