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.
# Enter your code here. Read input from STDIN. Print output to STDOUTimportcopy# Insertion sort Swapsdefinsertion_sort(arr):n=len(arr)counter_for_swaps=0foriinrange(1,n):val=arr[i]j=i-1while(j>=0andarr[j]>val):arr[j+1]=arr[j]counter_for_swaps+=1j-=1arr[j+1]=val# print(*arr)returncounter_for_swapsclassInsertion:def__init__(self):self.count=0definsertionsort(self,a):foriinrange(1,len(a)):key=a[i]j=i-1whilej>=0anda[j]>key:self.count+=1a[j+1]=a[j]j-=1a[j+1]=keyreturnself.countclassQuickSort:def__init__(self):self.count=0defswap(self,b,c,d):temp=b[c]b[c]=b[d]b[d]=tempreturnbdefpartition(self,a,s,e):pivot=epindex=sforiinrange(s,e):ifa[i]<=a[pivot]:self.swap(a,i,pindex)self.count+=1pindex+=1self.count+=1self.swap(a,pindex,pivot)returnpindexdefquicksort(self,a,s,e):ifs<e:pIndex=self.partition(a,s,e)self.quicksort(a,s,pIndex-1)self.quicksort(a,pIndex+1,e)returnself.countif__name__=='__main__':N=int(input())original=list(map(int,input().split()))duplicate=copy.deepcopy(original)insertion_counter_for_swaps=insertion_sort(original)# print(insertion_counter_for_swaps)# Quickyquicksort=QuickSort()start=0end=N-1quicksort_counter_for_swaps=quicksort.quicksort(duplicate,start,end)print(insertion_counter_for_swaps-quicksort_counter_for_swaps)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Running Time of Quicksort
You are viewing a single comment's thread. Return to all comments →