Knowledge organisersSearching and sorting algorithms
Understand the main steps of each algorithm, Understand any pre-requisites of an algorithm, Apply the algorithm to a data set, Identify an algorithm if given the code or pseudocode for it
Insertion sort works by building a sorted section of the list one item at a time. Starting from the second item, each element is compared to those already sorted and inserted into its correct position. It is simple to understand and efficient for small to medium-sized lists, but slower than merge sort for very large datasets.
def insertion_sort(data):
for i in range(1, len(data)):
key = data[i]
j = i - 1
while j >= 0 and data[j] > key:
data[j + 1] = data[j]
j -= 1
data[j + 1] = key
return data
print(insertion_sort([5, 3, 9, 4, 7]))
# Output: [3, 4, 5, 7, 9]