Insertion Sort in Python
Here you will learn the program code of insertion sort in python programming. To write a Python program for insertion sort, you simply insert each element into its correct position in a sorted part of the list.
What is insertion sort in python
Insertion sort is a sorting algorithm that works by building a sorted list one element at a time. It starts by picking an element from the list and comparing it with the elements already in the sorted list. If the element is smaller than any of the elements in the sorted list, it is inserted into the proper position. This process is repeated until all the elements are sorted.
Insertion sort in python program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #insertion sort in python program def insertionSort(arr): # Traverse through 1 to len(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] arr = [] print("Enter 5 numbers ") for i in range(5): item = int(input('Input item : ')) arr.append(item) insertionSort(arr) print ("Sorted array are the following....") for i in range(len(arr)): print ("% d" % arr[i]) |
Output
Enter 5 numbers
Input item : 4
Input item : 2
Input item : 6
Input item : 3
Input item : 5
Sorted array are the following….
2
3
4
5
6
Check out our other Python Programming Examples