Skip to content

Create reversesort #11886

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions data_structures/reversesort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
def reverse_selection_sort(arr: list[int]) -> list[int]:
"""
Sorts an array using a modified selection sort algorithm where after finding
the minimum element, a subarray is reversed instead of swapping.

Parameters:
arr (list[int]): The list of integers to sort.

Returns:
list[int]: The sorted list of integers.

Example:
>>> reverse_selection_sort([64, 25, 12, 22, 11])
[11, 12, 22, 25, 64]

>>> reverse_selection_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]

>>> reverse_selection_sort([3, 1, 2])
[1, 2, 3]

>>> reverse_selection_sort([10])
[10]

>>> reverse_selection_sort([])
[]
"""

n = len(arr)

# Iterate over each position of the array
for i in range(n - 1):
# Find the index of the minimum element in the unsorted portion
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j

# If the minimum is not already at position i, reverse the subarray
if min_index != i:
# Reverse the subarray from position i to min_index
arr[i : min_index + 1] = reversed(arr[i : min_index + 1])

return arr


if __name__ == "__main__":
import doctest

doctest.testmod()