grokking-algorithms/chapter2/selectionsort.py

32 lines
788 B
Python
Raw Normal View History

2024-01-05 12:25:49 +00:00
import logging
from collections import namedtuple
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
Data = namedtuple("Data", "artist count")
artists = [
Data("Said Mike", 156),
Data("The Blackout", 141),
Data("Hondo Maclean", 35),
Data("Enter Shikari", 94),
Data("FFAF", 88),
]
def selectionSort(array, size):
2024-01-05 12:37:49 +00:00
for index in range(size):
min_index = index
2024-01-05 12:25:49 +00:00
2024-01-05 12:37:49 +00:00
for j in range(index + 1, size):
2024-01-05 12:25:49 +00:00
# select the minimum element in every iteration
if array[j].count < array[min_index].count:
min_index = j
# swapping the elements to sort the array
2024-01-05 12:37:49 +00:00
(array[index], array[min_index]) = (array[min_index], array[index])
2024-01-05 12:25:49 +00:00
selectionSort(artists, len(artists))
print(artists)