Write a Program to Perform Insertion Sort in Python

Introduction

Insertion sort is one of the sort techniques for sorting array-based data. The name insertion is because it inserts the smallest element at the right position in each iteration by comparing it with the data before it(opposite case for the descending order). In this tutorial, you'll learn how to perform insertion sort in python.

How Insertion Sort Works

Step 1

iteration 1: It shows how does insertion sort algorithm works

Step 2

iteration 2: It shows how does insertion sort algorithm works

Step 3

iteration 3: It shows how does insertion sort algorithm works

Algorithm for Insertion Sort


length = Length of the Array
for i in (1 to length - 1)
item = array[i]
j = i - 1
# For desecding order: change '<' to '>'
while j >= 0 and (item < array[j])
array[j+1] = array[j]
j = j - 1
array[j+1] = item

Code


'''Write a program for insertion sort in python'''
def InsertionSort(array):
for i in range(1, len(array)):
item = array[i]
j = i - 1
while j >= 0 and (item < array[j]):
array[j+1] = array[j]
j -= 1
array[j+1] = item
# The main function
if __name__ == "__main__":
arr = [7, 8, 5, 2, 3]
InsertionSort(arr)
print("----The Sorted data----")
print(arr)

Output

----The Sorted data----
[2, 3, 5, 7, 8]

Insertion Sort with user input

Code


'''Program for insertion sort in python with user input'''
def InsertionSort(array):
for i in range(1, len(array)):
item = array[i]
j = i - 1
while j >= 0 and (item < array[j]):
array[j+1] = array[j]
j -= 1
array[j+1] = item
# The main function
if __name__ == "__main__":
arr = input("Enter the array data, separated by a comma: ").split(',')
arr = [int(i) for i in arr]
InsertionSort(arr)
print("----The Sorted data----")
print(arr)

Output

Enter the array data, separated by a comma: 7, 8, 5, 2, 3
----The Sorted data----
[2, 3, 5, 7, 8]

Complexity analysis

There are three conditions the array may have: In ascending order, descending order, or random order. The worst and average case occurs when the array of data is in descending or random order, and the best case occurs when the array is already sorted.

Time Complexity

Worst Case: O(n^2)

Average Case: O(n^2)

Best Case: O(n)

Space Complexity

For all conditions: O(1)

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post