mirror of
https://github.com/onyx-and-iris/grokking-algorithms.git
synced 2026-04-16 11:33:34 +00:00
reorganise directories
upd chapter_01/binary.py
This commit is contained in:
7
chapter_02/README.md
Normal file
7
chapter_02/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# Selection Sort
|
||||
|
||||
We have to perform N swaps a total of N times. This takes N^N steps, therefore:
|
||||
|
||||
This algorithm has time complexity `O(N^2)`
|
||||
|
||||
Technically (`n – 1, n - 2 ... 2, 1` ~= N/2) swaps are performed but in BigO the constants are dropped.
|
||||
31
chapter_02/selectionsort.py
Normal file
31
chapter_02/selectionsort.py
Normal file
@@ -0,0 +1,31 @@
|
||||
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):
|
||||
for index in range(size):
|
||||
min_index = index
|
||||
|
||||
for j in range(index + 1, size):
|
||||
# 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
|
||||
(array[index], array[min_index]) = (array[min_index], array[index])
|
||||
|
||||
|
||||
selectionSort(artists, len(artists))
|
||||
print(artists)
|
||||
Reference in New Issue
Block a user