Skip to content

Create exchange_sort.py #4600

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

Merged
merged 4 commits into from
Aug 15, 2021
Merged
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
27 changes: 27 additions & 0 deletions sorts/exchange_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
def exchange_sort(numbers: list[int]) -> list[int]:
"""
Uses exchange sort to sort a list of numbers.
Source: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort
>>> exchange_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> exchange_sort([-1, -2, -3])
[-3, -2, -1]
>>> exchange_sort([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> exchange_sort([0, 10, -2, 5, 3])
[-2, 0, 3, 5, 10]
>>> exchange_sort([])
[]
"""
numbers_length = len(numbers)
for i in range(numbers_length):
for j in range(i + 1, numbers_length):
if numbers[j] < numbers[i]:
numbers[i], numbers[j] = numbers[j], numbers[i]
return numbers


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