Python Insertion Sort

After learning about classes in python, today in this post we shall use those concepts in making insertion sort program. Insertion sort is one of the basic sorting techniques other than, bubble sort.

It compares key element with the previous element. If the key element is less than previous element, then those two elements are swapped and again the key element is compared with previous element and process goes on.

We could sort data either in ascending order or descending order.

class insertion(object):
	"""docstring for ClassName"""
	def __init__(self, size, ch):
		self.size = size = ch = []
		for i in range(size):"Enter number into list:"))
		if(ch == 1):
	def ascsorting(self):
		for i in range(1,self.size):
			j = i
			while  j > 0 and int([j-1]) > int([j]):[j-1],[j] =[j],[j-1]
				j= j-1
		print ("\nSorted Data is: " + str(
	def dscsorting(self):
		for i in range(1, self.size):
			j = i
			while j>0 and int([j-1]) < int([j]):[j-1],[j] =[j],[j-1]
				j = j-1
		print ("\nSorted Data is " + str(

ch = int(input("Enter choice according to order of sort 1.ascending order 2. Descending order: "))
size = int(input("Enter size of the list: "))
a = insertion(size, ch)

In the above code, we have created a class called insertion to direct the sorting either in ascending order or descending order. The method __init__(self, size, ch) is constructor for insertionn class. It takes three arguments, self which is default argument used to point the class variables. “size” argument is passed during the creation of object for insertion class which says, the number of elements in the given list. “ch” argument is for either ascending order or descending order.

Download the Source Code


About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Python and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s