Take the next value and slide it left into its place among the already sorted ones, like sorting cards in your hand.
Python · intermediate · 7 min · 35 steps · free
def insertion_sort(items):
for i in range(1, len(items)):
current = items[i]
j = i - 1
while j >= 0 and items[j] > current:
items[j + 1] = items[j]
j -= 1
items[j + 1] = current
return items
print(insertion_sort([7, 4, 5, 2]))insertion_sort(). Its body does not run yet: it runs each time the function is called.insertion_sort(), with items = [7, 4, 5, 2]. It gets its own names.i is created with the value 1.current = 4 is the card to insert into the sorted part [7].j is created with the value 0.j >= 0 and items[j] > current is true, so the loop body runs.j changes from 0 to -1.j >= 0 and items[j] > current is false, so the loop ends.i changes from 1 to 2.current changes from 4 to 5.j changes from -1 to 1.j >= 0 and items[j] > current is true, so the loop body runs.items points to, index 2 changes from 5 to 7.j changes from 1 to 0.j >= 0 and items[j] > current is false, so the loop ends.items points to, index 1 changes from 7 to 5.i changes from 2 to 3.j changes from 0 to 2.j >= 0 and items[j] > current is true, so the loop body runs.items points to, index 3 changes from 2 to 7.j changes from 2 to 1.j >= 0 and items[j] > current is true, so the loop body runs.items points to, index 2 changes from 7 to 5.j changes from 1 to 0.j >= 0 and items[j] > current is true, so the loop body runs.items points to, index 1 changes from 5 to 4.j changes from 0 to -1.j >= 0 and items[j] > current is false, so the loop ends.for i in range(1, len(items)).items.insertion_sort() has finished, so its names are gone. It prints [2, 4, 5, 7].currentAnswer: O(n). No shifts needed.
Answer: Shifts bigger values right
← Selection Sort · Merge Sort →