Skip to content

Commit c83c414

Browse files
Create ReverSort.py
I noticed that the repository has a variety of sorting algorithms but does not include the Reversort algorithm, which is a unique and interesting sorting method. Reversort, popularized by Google Code Jam, involves repeatedly reversing subarrays to sort the list. This algorithm differs from traditional sorting algorithms like selection sort and adds a fun twist to sorting problems. Key Characteristics of the Reversort Algorithm: 1. The algorithm iteratively finds the minimum element from the unsorted portion of the list. 2. Instead of swapping, it reverses the entire subarray between the current index and the minimum element’s index to bring the smallest element to its correct position. 3. This process continues until the list is sorted.
1 parent fcf82a1 commit c83c414

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

sorts/ReverSort.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
def reversort(collection: list[int]) -> list[int]:
2+
"""
3+
Sorts a list in ascending order using the Reversort algorithm.
4+
5+
:param collection: A list of integers to be sorted.
6+
:return: The sorted list.
7+
8+
Examples:
9+
>>> reversort([4, 2, 1, 3])
10+
[1, 2, 3, 4]
11+
12+
>>> reversort([5, 6, 3, 2, 8])
13+
[2, 3, 5, 6, 8]
14+
15+
>>> reversort([7])
16+
[7]
17+
"""
18+
19+
length = len(collection)
20+
for i in range(length - 1):
21+
# Find the index of the minimum element in the subarray collection[i:]
22+
j = min(range(i, length), key=collection.__getitem__)
23+
# Reverse the subarray collection[i:j+1]
24+
collection[i:j + 1] = collection[i:j + 1][::-1]
25+
return collection
26+
27+
28+
if __name__ == "__main__":
29+
user_input = input("Enter numbers separated by a comma:\n").strip()
30+
unsorted = [int(item) for item in user_input.split(",")]
31+
sorted_list = reversort(unsorted)
32+
print("Sorted List:", sorted_list)

0 commit comments

Comments
 (0)