Running Time of Quicksort

  • + 0 comments
    # Enter your code here. Read input from STDIN. Print output to STDOUT
    import copy
    # Insertion sort Swaps
    def insertion_sort(arr):
        n = len(arr)
        counter_for_swaps = 0
        for i in range(1, n):
            val = arr[i]
            j = i-1
    
            while(j >= 0 and arr[j] > val):
                arr[j+1] = arr[j]
                counter_for_swaps += 1
                j -= 1
    
            arr[j+1] = val
        # print(*arr)
        return counter_for_swaps
    
    class Insertion:
        def __init__(self):
            self.count=0
        def insertionsort(self,a):
            for i in range(1,len(a)):
                key=a[i]
                j=i-1
                while j>=0 and a[j]>key:
                    self.count+=1
                    a[j+1]=a[j]
                    j-=1
                a[j+1]=key
            return self.count
    
    class QuickSort:
        def __init__(self):
            self.count=0
        def swap(self,b,c,d):
            temp=b[c]
            b[c]=b[d]
            b[d]=temp
            return b
        def partition(self,a,s,e):
            pivot=e
            pindex=s
            for i in range(s,e):
                if a[i]<=a[pivot]:
                    self.swap(a,i,pindex)
                    self.count+=1
                    pindex+=1
            self.count+=1
            self.swap(a,pindex,pivot)
            return pindex
        def quicksort(self,a,s,e):
            if s<e:
                pIndex=self.partition(a,s,e)
                self.quicksort(a, s, pIndex-1)
                self.quicksort(a, pIndex+1, e)
            return self.count
        
    if __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)
    
        # Quicky
        quicksort=QuickSort()
        start = 0
        end = N -1
        quicksort_counter_for_swaps = quicksort.quicksort(duplicate, start, end)
        print(insertion_counter_for_swaps - quicksort_counter_for_swaps)