Skip to content

Commit 032999f

Browse files
authored
Create exchange_sort.py (TheAlgorithms#4600)
* Create exchange_sort.py added exchange sort * Fixed doctest in exchange_sort.py * Fixed formatting error and added new length variable added empty line at end of exchange_sort.py and turned len(numbers) into a variable * Fixed formatting errors with black added empty line
1 parent 3c22524 commit 032999f

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

sorts/exchange_sort.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
def exchange_sort(numbers: list[int]) -> list[int]:
2+
"""
3+
Uses exchange sort to sort a list of numbers.
4+
Source: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort
5+
>>> exchange_sort([5, 4, 3, 2, 1])
6+
[1, 2, 3, 4, 5]
7+
>>> exchange_sort([-1, -2, -3])
8+
[-3, -2, -1]
9+
>>> exchange_sort([1, 2, 3, 4, 5])
10+
[1, 2, 3, 4, 5]
11+
>>> exchange_sort([0, 10, -2, 5, 3])
12+
[-2, 0, 3, 5, 10]
13+
>>> exchange_sort([])
14+
[]
15+
"""
16+
numbers_length = len(numbers)
17+
for i in range(numbers_length):
18+
for j in range(i + 1, numbers_length):
19+
if numbers[j] < numbers[i]:
20+
numbers[i], numbers[j] = numbers[j], numbers[i]
21+
return numbers
22+
23+
24+
if __name__ == "__main__":
25+
user_input = input("Enter numbers separated by a comma:\n").strip()
26+
unsorted = [int(item) for item in user_input.split(",")]
27+
print(exchange_sort(unsorted))

0 commit comments

Comments
 (0)