简体   繁体   中英

Printing when Searching for Inversions

I'm trying to implement an algorithm that searches for inversions. I'm having trouble printing the updated global variable c . Where should I put the print statement?

I'd prefer using a method that involves the boilerplate(?) because I'm going to run a timing function to test the running time later. If I could only get it to print the result (8). If I put it inside the merge function(before return C) it returns all the values up to 8. I want it to just print c at the end of the process.

c=0
def merge(A,B):

    global c
    C=[]
    lenA=len(A)
    lenB=len(B)
    i=0
    j=0
    while i<lenA and j<lenB:
        if A[i]<=B[j]:
            C.append(A[i])
            i=i+1
        else:
            c=c+len(A)-i 
            C.append(B[j])
            j=j+1
    if i==lenA:  #A get to the end
        C.extend(B[j:])
    else:
        C.extend(A[i:])
    return C


def inversions_divide_conquer(Array):
    N=len(Array)
    if N>1:
        S1=inversions_divide_conquer(Array[0:N/2])
        S2=inversions_divide_conquer(Array[N/2:])
        return merge(S1,S2)
    else:
        return Array



if __name__ == '__main__':

    inversions_divide_conquer([4, 1, 3, 2, 9, 1])
M = len(stuff)
def inversions_divide_conquer(Array):
    N=len(Array)
    if N>1:
        S1=inversions_divide_conquer(Array[0:N/2])
        S2=inversions_divide_conquer(Array[N/2:])
        if N == M:
            print c
        return merge(S1,S2)
    else:
        return Array

inversions_divide_conquer(stuff)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM