Insertion Sort
excerpt: How does insertionsort work? What is the time complexity? When can we use insertionsort? tags: nestedloopwithforandwhile shiftright forwardandbackwardnestedloops
The goal is to order a list of integers in ascending order. The insertion sort is quadratic in time complexity but simple. It can outperform faster but more complicated algorithms for very small arrays.
The shift right is a basic building block for insertion sort. For example, the array [1, 2, 3] shifted right by one unit will be [3, 1, 2]. The implementation:


The last element is saved in the variable called element. The array is processed from the right because we have a free slot to the right, this gets the value of the preceding element. The last element is copied to the first location outside the loop.
Insertionsort in Arrays
An item is taken from the input list and inserted into the proper position in a sorted output list.
 Iterate from 0 to array size  1
 Move item i into position in the sorted part of the array.
 Find the index j where j < i and values[j] > values[i]
 Move the item into position j
 Repeat steps 1 and 2 for all elements in the array.
Iterate through the items in the array, the index i separates the items that have been sorted from those that are unsorted. The items with an index < i have already been sorted and those with an index >= i have not yet been sorted.
As i goes from 0 to the last index in the array, the item at index i is moved into the proper position in the sorted part of the array. The item’s position is found by looking through the already sorted items and finding the first item that is > values[i].
The element at values[i] is moved into its new position. This step can be time consuming. Suppose the item’s new index should be j. In that case, the items must be moved between indices j and i one position to the right to make room for the item at position j.
The key steps of the algorithm is shown in the diagrams. The first image shows the unsorted array. The second image shows the first four items as sorted and the code is preparing to insert the next item, 3 into the sorted part of the array. The code searches through the sorted items untils it determines the value 3 should be inserted before the value 5. The last image shows that the values 5,6 and 7 have moved to the right to make room for value 3. The value 3 is inserted and the for loop continues to insert the next item 2 into its correct position.
This algorithm sorts the items inplace so it does not require any additional space. If the array contains N items, each of the N positions in the array is considered. For each position i, it must search the previously sorted items in the array to find the ith item’s new position. It must then move the items between that location and index i one position to the right. If the item i should be moved to position j, it takes j steps to find the new location j and then i  j more steps to move items over, resulting in a total of i steps. That means in total it takes i steps to move item i into its new position.
The total run time is calculated by adding up all the steps required to position all the items.
1 + 2 + 3 + … + N = (N2 + N)/2
The run time is O(N2). This is fast enough for small arrays of size 10,000 or so. This algorithm is relatively simpler that complicated algorithms that are faster.
Implementation
Consider the list as if it was divided into two parts, one sorted and the other unsorted. At the beginning the sorted part is empty.
 Select the first element of the unsorted part of the list
 Insert such an element into its correct position in the sorted part of the list.
 Change where you divide the array from the sorted part to the unsorted part.
Mechanism is similar to inserting (adding) an element to an array list: Shift all elements ahead by one position to make a hole, and then fill the hole. The solution outline is shown below:
 Repeat until list is all sorted (~N times).
 Find where the element should be inserted in the sorted part of the list + make space for it (shift all the larger elements to the right).
 Insert the element in the sorted part of the list.


Alternative Implementation
Work on the array insert drill before the following insertion sort implementation.


Building Blocks
The insertion sort algorithm uses the following basic building block:
 Nested Loop with For and While
 Nested Forward and Backward Loops
 Right Shift
Language Agnostic Coding Drills
Here’s a breakdown of the key learning units for the Insertion Sort algorithm:
Iteration and Looping: Understanding the concept of iteration, particularly how
for
andwhile
loops work. Insertion sort involves moving through an array multiple times.List Indexing: Being able to index into a list to get, set, and compare values. Insertion sort constantly accesses and modifies elements at different positions in a list.
Nested Looping: Insertion sort involves a nested loop where for each element, the algorithm iterates over all the previous elements.
Variable Updating: The ability to update the value of a variable. Insertion sort includes updating the current index and the current value to be sorted.
Condition Checking: Understanding ifelse conditions. Insertion sort involves a key comparison operation to check whether one element is greater than another.
Swapping Elements: In insertion sort, when the current element is less than the previous element, the algorithm performs a swap.
Problem Decomposition: Understanding how to decompose the insertion sort problem into smaller, manageable tasks that correspond to the steps of the algorithm.
Algorithm Analysis: Understand how to analyze the time and space complexity of insertion sort algorithm.
Complete Insertion Sort Algorithm: Bringing all these units together to understand and implement the full insertion sort algorithm.
Solution for Coding Drills in Python
Here are Python code examples for each of the learning units:
 Iteration and Looping:


 List Indexing:


 Nested Looping:


 Variable Updating:


 Condition Checking:


 Swapping Elements:


 Problem Decomposition: Not applicable as it’s a cognitive skill rather than a coding skill.
 Algorithm Analysis: Not applicable as it’s a theoretical aspect of computer science, not a Python coding skill.
 Complete Insertion Sort Algorithm:


Sure, here’s a general template for practicing insertion sort. This example sorts an array of integers in ascending order.
Understand the problem: Given an array of integers, sort them in increasing order using insertion sort.
Plan: Insertion sort works by maintaining a sorted section of the array, and with each iteration, it expands this sorted section by one element, placing the new element in the correct position.
Code:


Review: Test the function with various input arrays to ensure it sorts correctly. If there are any bugs, review your implementation against the algorithm and correct them.
Test:


This should print:
Original array: [4, 3, 2, 10, 12, 1, 5, 6]
Sorted array: [1, 2, 3, 4, 5, 6, 10, 12]
Please note that the above code is in Python, so you might need to adjust it based on the language you’re using. Insertion sort is best suited for nearly sorted arrays or smallsized arrays, as its worstcase and average time complexity is O(n^2), where n is the number of elements in the array.
Practice Phase Template for Insertion Sort
Sure, here’s a general template for practicing insertion sort. This example sorts an array of integers in ascending order.
Understand the problem: Given an array of integers, sort them in increasing order using insertion sort.
Plan: Insertion sort works by maintaining a sorted section of the array, and with each iteration, it expands this sorted section by one element, placing the new element in the correct position.
Code:


Review: Test the function with various input arrays to ensure it sorts correctly. If there are any bugs, review your implementation against the algorithm and correct them.
Test:


This should print:
Original array: [4, 3, 2, 10, 12, 1, 5, 6]
Sorted array: [1, 2, 3, 4, 5, 6, 10, 12]
Insertion sort is best suited for nearly sorted arrays or smallsized arrays, as its worstcase and average time complexity is O(n^2), where n is the number of elements in the array.