forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexchange_sort.py
More file actions
35 lines (26 loc) · 817 Bytes
/
exchange_sort.py
File metadata and controls
35 lines (26 loc) · 817 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
Exchange Sort
Exchange sort compares every pair of elements and swaps them if they are
out of order. It is conceptually similar to bubble sort.
Reference: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort
Complexity:
Time: O(n^2) best / O(n^2) average / O(n^2) worst
Space: O(1)
"""
from __future__ import annotations
def exchange_sort(array: list[int]) -> list[int]:
"""Sort an array in ascending order using exchange sort.
Args:
array: List of integers to sort.
Returns:
A sorted list.
Examples:
>>> exchange_sort([3, 1, 2])
[1, 2, 3]
"""
n = len(array)
for i in range(n - 1):
for j in range(i + 1, n):
if array[i] > array[j]:
array[i], array[j] = array[j], array[i]
return array