Insertion Sort Python (original) (raw)

Last Updated : 12 Nov, 2025

Insertion Sort is a simple and intuitive sorting algorithm that works by building a sorted list one element at a time. It takes each element from the unsorted portion and inserts it into the correct position in the sorted portion.

Insertion-sorting

Insertion Sort

How Insertion Sort Works

  1. Start from the second element (as the first one is already considered sorted).
  2. Compare the current element (called key) with the elements before it.
  3. Shift all larger elements one position to the right.
  4. Insert the key into its correct position.
  5. Repeat until the entire array is sorted.

Python Implementation

Python `

def insertionSort(arr): n = len(arr)

if n <= 1:
    return
for i in range(1, n):
    key = arr[i]         
    j = i - 1
    while j >= 0 and key < arr[j]: 
        arr[j + 1] = arr[j]
        j -= 1
    arr[j + 1] = key      

arr = [12, 11, 13, 5, -1] insertionSort(arr) print(arr)

`

Output

[-1, 5, 11, 12, 13]

**Explanation: