Find the smallest remaining value and swap it into the next place. One swap per pass.
Python · intermediate · 6 min · 31 steps · free
def selection_sort(items):
for start in range(len(items) - 1):
smallest = start
for i in range(start + 1, len(items)):
if items[i] < items[smallest]:
smallest = i
items[start], items[smallest] = items[smallest], items[start]
return items
print(selection_sort([29, 10, 14, 37]))selection_sort(). Its body does not run yet: it runs each time the function is called.selection_sort(), with items = [29, 10, 14, 37]. It gets its own names.start is created with the value 0.smallest starts as the first unsorted index.i is created with the value 1.items[i] < items[smallest] is true, so the block under it runs.i changes from 1 to 2.items[i] < items[smallest] is false, so the block under it is skipped.i changes from 2 to 3.items[i] < items[smallest] is false, so the block under it is skipped.for i in range(start + 1, len(items)).start changes from 0 to 1.smallest = start.i changes from 3 to 2.items[i] < items[smallest] is true, so the block under it runs.smallest changes from 1 to 2.i changes from 2 to 3.items[i] < items[smallest] is false, so the block under it is skipped.for i in range(start + 1, len(items)).items points to, index 1 changes from 29 to 14 and index 2 changes from 14 to 29.start changes from 1 to 2.smallest = start.for i in range(start + 1, len(items)).items[i] < items[smallest] is false, so the block under it is skipped.for i in range(start + 1, len(items)).items[start], items[smallest] = items[smallest], items[start].for start in range(len(items) - 1).selection_sort() has finished, so its names are gone. It prints [10, 14, 29, 37].Answer: n - 1
Answer: No. It still scans everything.
← Bubble Sort · Insertion Sort →