Running Time of Quicksort

  • + 0 comments
    # Enter your code here. Read input from STDIN. Print output to STDOUT
    
    def runningTimeIn(arr):
        count = 0
        for i in range(1,len(arr)):
            j = i-1
            key = arr[i]
            while (j>=0) and (arr[j]>key):
                arr[j+1]=arr[j]
                j -= 1
                count += 1
            arr[j+1]=key
        return count
    
    def partition(arr,low,high,swap):
        i = ( low-1 )         
        pivot = arr[high] 
        #swaps = 0
        for j in range(low , high): 
            if   arr[j] <= pivot: 
                i = i+1 
                arr[i],arr[j] = arr[j],arr[i]
                swap += 1
      
        arr[i+1],arr[high] = arr[high],arr[i+1] 
        swap += 1
        return i+1,swap 
      
    def runningTimeQ(arr,low,high,swap=0): 
        pi = 0
        if low < high:
            pi,swap = partition(arr,low,high,swap) 
            #print (' '.join(map(str, arr)))
            swap = runningTimeQ(arr, low, pi-1,swap) 
            swap = runningTimeQ(arr, pi+1, high,swap) 
        return swap
    
    if __name__ == '__main__':
        n = int(input())
    
        arr = list(map(int, input().rstrip().split()))
    
        arrCopy = []
        arrCopy.extend(arr)
        
        qRun = runningTimeQ(arr,0,n-1)
        
        inRun = runningTimeIn(arrCopy)
        
        result = inRun - qRun 
    
        print(result)