DSA — Insertion Sort
What is Insertion Sort?
Builds the sorted array one element at a time by inserting each element into its correct position.
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
return arr
How it Works
[12, 11, 13, 5, 6]
↓
[11, 12, 13, 5, 6]
↓
[11, 12, 13, 5, 6]
↓
[5, 11, 12, 13, 6]
↓
[5, 6, 11, 12, 13]
Time Complexity
| Case | Complexity |
|---|---|
| Best | O(n) |
| Average | O(n²) |
| Worst | O(n²) |
Characteristics
- Stable sort
- In-place
- Efficient for small datasets
- Adaptive (fast on nearly sorted data)
Mini Practice
- Implement insertion sort
- Sort cards like a card player
- Use for online sorting
- Compare with other sorts
Up Next
Continue with Merge Sort — divide and conquer sorting.
Related Topics
Frequently Asked Questions about Insertion Sort
What is Insertion Sort in DSA?
Insertion Sort is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Insertion Sort?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Insertion Sort.
Why is Insertion Sort important in DSA?
Insertion Sort is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.