-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathselection_sort.py
38 lines (32 loc) · 1.13 KB
/
selection_sort.py
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
36
37
38
def selection_sort(unsorted: list):
"""
# Selection Sort
Selection sort is another sorting algorithm, which compares smallest of all
values and and put it in the first position. Similarly, after swapping value,
it will find out second most smallest value and swap it with second item in
the array.
Unlike bubble sort, the sorting will be done from the beginning.
## Example:
- 4 2 9 0 7 5 1 <- Swap 4 and 0
- ^ ^
- [0] 2 9 4 7 5 1 <- 0 is sorted
- [0] 2 9 4 7 5 1 <- Swap 2 and 1
- ^ ^
-...
Swap values until all values are sorted
"""
for index in range(0, unsorted.__len__()):
smallest = index
for target in range(index, unsorted.__len__()):
if unsorted[smallest] > unsorted[target]:
smallest = target
if smallest != index:
unsorted[index], unsorted[smallest] = (
unsorted[smallest],
unsorted[index],
)
if __name__ == "__main__":
my_list = [4, 2, 9, 0, 7, 5, 1]
print(f"Unsorted: {my_list}")
selection_sort(my_list)
print(f"Sorted: {my_list}")