Skip to content

Commit 797703b

Browse files
style: Add type hints and doctest to sorts/exchange_sort.py
1 parent e2a78d4 commit 797703b

File tree

1 file changed

+20
-24
lines changed

1 file changed

+20
-24
lines changed

sorts/exchange_sort.py

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,23 @@
1-
def exchange_sort(numbers: list[int]) -> list[int]:
1+
def exchange_sort(data: list) -> list:
22
"""
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
3+
Sorts a list of elements using the Exchange Sort algorithm.
4+
5+
Exchange Sort is a variant of Bubble Sort, swapping elements if they
6+
are found to be out of order.
227
8+
Examples:
9+
>>> exchange_sort([5, 2, 9, 1, 5])
10+
[1, 2, 5, 5, 9]
11+
>>> exchange_sort([10, 5, 3, 2])
12+
[2, 3, 5, 10]
13+
"""
14+
n = len(data)
15+
for i in range(n):
16+
for j in range(i + 1, n):
17+
if data[i] > data[j]:
18+
data[i], data[j] = data[j], data[i]
19+
return data
2320

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))
21+
if __name__ == '__main__':
22+
import doctest
23+
doctest.testmod()

0 commit comments

Comments
 (0)