Python Insertion Sort


Insertion Sort builds the final sorted list one element at a time. It is simple, intuitive, and works well with small or nearly sorted lists.

It’s the same way we often sort playing cards in our hands!


🔹 How Insertion Sort Works

  1. Start from the second element

  2. Compare it with elements before

  3. Shift larger elements one position to the right

  4. Insert the current element into its correct position

  5. Repeat for all elements


🔹 Insertion Sort in Python

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1

        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1

        arr[j + 1] = key

Example
numbers = [12, 11, 13, 5, 6]

insertion_sort(numbers)
print("Sorted array:", numbers)

✅ Output:

Sorted array: [5, 6, 11, 12, 13]

🔹 Visual Example (First 2 Steps)

Start: [12, 11, 13, 5, 6]
→ Compare 11 with 12 → [11, 12, 13, 5, 6]
→ Compare 13 with 12 → No change


🔹 Time Complexity

Case Time
Best Case O(n)
Average O(n²)
Worst Case O(n²)
Space O(1)

It performs better than bubble/selection sort for nearly sorted lists.


🔹 Use Cases of Insertion Sort

  • Best for small datasets

  • When input is already partially sorted

  • Stable sort (preserves order of equal elements)


Practice Questions

Q1. Write a Python program to sort the list [7, 3, 5, 2] using insertion sort.

Q2. Write a Python program to modify insertion sort to sort a list in descending order.

Q3. Write a Python program to accept a list of numbers from the user and sort them using insertion sort.

Q4. Write a Python program to count and print how many times the array is modified during insertion sort.

Q5. Write a Python program to sort a list of strings alphabetically using insertion sort.

Q6. Write a Python program to print the list after each insertion step during insertion sort.

Q7. Write a Python program to sort only the first half of a list using insertion sort.

Q8. Write a Python program to implement insertion sort without using a separate function (write code directly in the main block).

Q9. Write a Python program to sort a list using reverse logic in insertion sort (from end to start).

Q10. Write a Python program to compare the time taken by insertion sort and selection sort to sort a list of 1,000 random numbers.


Go Back Top