Back to Home

Insertion Sort

A simple sorting algorithm that builds the final sorted array one item at a time, inserting each new item into its proper place.

Visualization

Step 1 / 16
Speed:

Details

Analogy

This is like how most people sort a hand of playing cards. You hold the sorted cards in one hand. You pick up a new card from the pile and slide it into the correct position within your hand, shifting other cards as necessary to make room.

Purpose

To sort an array by taking one element from the unsorted part and finding its correct position in the sorted part.

Use Cases

Efficient for small datasets and for datasets that are already substantially sorted. It's adaptive and stable.

Algorithm Steps

Line 1
1
for i = 1 to n:
2
key = arr[i]
3
j = i - 1
4
while j >= 0 and arr[j] > key:
5
arr[j+1] = arr[j]
6
j = j - 1
7
arr[j+1] = key
Current
Executed
Pending

Explanation

What's Happening?

Step 1/16

Start. The first element, 12, is considered sorted.

Updates with each step • Clickfor full view

Code Implementation

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and key < arr[j]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    return arr
Insertion Sort - Interactive Visualization | AlgoViz | AlgoViz