Insertion Sort is a simple sorting algorithm that builds the final sorted list one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, it provides several advantages:
Imagine you are sorting a hand of playing cards. You pick up one card at a time and insert it into its correct position in the cards you are already holding.
key element you want to insert into the sorted sublist.key with the elements in the sorted sublist, moving from right to left.key one position to the right.key into the gap you've created.Here is a function that implements the insertion sort algorithm.
def insertion_sort(data):
# Traverse through 1 to len(data)
for i in range(1, len(data)):
key = data[i]
# Move elements of data[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i - 1
while j >= 0 and key < data[j]:
data[j + 1] = data[j]
j -= 1
data[j + 1] = key
--- Usage ---
my_list = [12, 11, 13, 5, 6]
insertion_sort(my_list)
print("Sorted list is:", my_list)
while loop is never entered, and it only takes one pass.Practical Use: Because of its O(n) best-case performance, insertion sort is often used as the final step in more complex sorting algorithms, like Timsort (Python's default sorting algorithm), to sort small, nearly-sorted partitions of a larger list.
In which scenario is Insertion Sort most efficient?