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 self.ch = ch self.data = [] for i in range(size): self.data.append(input("Enter number into list:")) if(ch == 1): self.ascsorting() else: self.dscsorting() def ascsorting(self): for i in range(1,self.size): j = i while j > 0 and int(self.data[j-1]) > int(self.data[j]): self.data[j-1], self.data[j] = self.data[j], self.data[j-1] j= j-1 print ("\nSorted Data is: " + str(self.data)) def dscsorting(self): for i in range(1, self.size): j = i while j>0 and int(self.data[j-1]) < int(self.data[j]): self.data[j-1], self.data[j] = self.data[j], self.data[j-1] j = j-1 print ("\nSorted Data is " + str(self.data)) 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.
Output: