-
Hajipur, Bihar, 844101
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!
Start from the second element
Compare it with elements before
Shift larger elements one position to the right
Insert the current element into its correct position
Repeat for all elements
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
numbers = [12, 11, 13, 5, 6]
insertion_sort(numbers)
print("Sorted array:", numbers)
✅ Output:
Sorted array: [5, 6, 11, 12, 13]
Start: [12, 11, 13, 5, 6]
→ Compare 11 with 12 → [11, 12, 13, 5, 6]
→ Compare 13 with 12 → No change
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.
Best for small datasets
When input is already partially sorted
Stable sort (preserves order of equal elements)
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.
Q1: What is the key idea of insertion sort?
Q2: In which case is insertion sort most efficient?
Q3: Which sort works like sorting cards in hand?
Q4: What is the worst-case time complexity?
Q5: What happens when current element is smaller than all before?
Q6: Insertion sort is a __________ sort.
Q7: Which loop is commonly used to shift elements in Insertion Sort?
Q8: Can Insertion Sort be used to sort strings?
Q9: Space complexity of insertion sort?
Q10: What happens after each outer loop iteration in Insertion Sort?