We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#!/bin/python3importmathimportosimportrandomimportreimportsys## Complete the 'insertionSort2' function below.## The function accepts following parameters:# 1. INTEGER n# 2. INTEGER_ARRAY arr#classInsertionSort:def__init__(self,arr):self.arr=arrself.n=len(arr)self.history=[]defsort(self):foriinrange(1,self.n):self.insert_and_track(i)self.track_state()#Ensurestateistrackedaftereachpassself.print_history()definsert_and_track(self,i):key=self.arr[i]j=i-1whilej>=0andself.arr[j]>key:self.arr[j+1]=self.arr[j]j-=1self.arr[j+1]=keydeftrack_state(self):self.history.append(self.arr.copy())defprint_history(self):forstateinself.history:print(" ".join(map(str,state)))if__name__=='__main__':n=int(input().strip())arr=list(map(int,input().rstrip().split()))sorter=InsertionSort(arr)sorter.sort()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Insertion Sort - Part 2
You are viewing a single comment's thread. Return to all comments →
My solution using Python.