Signup/Sign In

Python program for Insertion sort

This tutorial will learn about the insertion sort algorithm and its implementation in Python.

Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration. Insertion sort works similarly as we sort cards in our hands in a card game. We assume that the first card is already sorted then, we select an unsorted card. If the unsorted card is greater than the card in hand, it is placed on the right otherwise, to the left. In the same way, other unsorted cards are taken and put in their right place.

As the output, we are required to get the sorted array.

Look at the given example to understand the working with input and output.

Input:

array: {3 5 1 2 6}

Output:

array: {1 2 3 5 6}

Input:

array: {56 9 11 7 60}

Output:

array: {7 9 11 56 60}

Algorithm

Step1: The first element in the array is assumed to be sorted. Take the second element and store it separately in "k". Compare "k" with the first element. If the first element is greater than "k", then "k" is placed in front of the first element.

Step2: Now, the first two elements are sorted. Take the third element and compare it with the elements on its left. Placed it just behind the element smaller than it. If there is no element smaller than it, then place it at the beginning of the array.

Step3: Similarly, place every unsorted element at its correct position.

Step4: The above process goes on until the last element.

Python program for Insertion Sort

# Python program for implementation of Insertion Sort

# Function to do insertion sort
def insertionSort(arr):

	# Traverse through 1 to len(arr)
	for i in range(1, len(arr)):

		key = arr[i]

		# Move elements of arr[0..i-1], that are
		# greater than key, to one position ahead
		# of their current position
		j = i-1
		while j >= 0 and key < arr[j] :
				arr[j + 1] = arr[j]
				j -= 1
		arr[j + 1] = key


# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
	print ("% d" % arr[i])


5, 6, 11, 12, 13

Conclusion

We have concluded the significance of insertion sort in this tutorial. Also, the implementation part has been shown to produce the program's desired output.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.