University-Docs/Documents/School/SEM 2/MI/insertion_sort.py

25 lines
688 B
Python

# voorbeeld code
def swap(values, i, j):
# temp = values[i]
# values[i] = values[j]
# values[j] = temp
values[i], values[j] = values[j], values[i]
def insertion_sort(values):
i = 1
# INVAR: is_sorted(values[:i])
while i < len(values):
j = i - 1
# INVAR: is_sorted(values[:j+1]) and is_sorted(values[j+1:i+1])
while j >= 0 and values[j] > values[j+1]:
swap(values, j, j+1)
j = j - 1
i = i + 1
return values # om te testen
assert insertion_sort([]) == []
assert insertion_sort([1]) == [1]
assert insertion_sort([2, 1]) == [1, 2]
assert insertion_sort([7, 2, 1, 4, 5, 3, 6]) == [1, 2, 3, 4, 5, 6, 7]