Python Program for Insertion Sort
In this tutorial, we will discuss a Python program for insertion sort algorithm to sort an array of numbers in ascending order.
Before going to the program first, let us understand what is Insertion Sort.
Insertion Sort:
- Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time.
Related: Python program for Bubble Sort
Program code for Insertion Sort in Python
# 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 key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
print("Sorted array:", arr)
Explanation
- Function Definition: The
insertion_sortfunction takes an arrayarras input and sorts it in ascending order using the insertion sort algorithm. - Main Program: The program defines an unsorted array and sorts it using the
insertion_sortfunction. It then prints the sorted array.
Output
- When you run the above program, it will sort the array using insertion sort and print the sorted result.
Conclusion
- In this tutorial, we learned how to implement the insertion sort algorithm in Python.
- Understanding this concept is essential for solving various sorting problems and enhancing your programming skills.

