简体   繁体   中英

Bug in count inversions algorithm

I am trying to write an algorithm to count the number of inversions in an array. An inversion is A[i] > A[j] and i < j.

def sort_and_count(L):
    if len(L)<2:
        return 0, L
    else:
        A = L[:len(L)//2]
        B = L[len(L)//2:]
        rA, A = sort_and_count(A)
        rB, B = sort_and_count(B)
        r, L = merge_and_count(A,B)
    return r+rB+rA, L

def merge_and_count(A,B):
    i = j = 0
    count = 0
    L = []
    while len(A) > i and len(B) > j:
        if A[i] <= B[j]:
            L.append(A[i])
            i+=1
        else:
            L.append(B[j])
            count = count + (len(A)-1)
            j+=1
    #copy the remaining elements
    for index in range(i,len(A)):
        L.append(A[index])
    for index in range(j,len(B)):
        L.append(B[index])
    return count, L

sort_and_count(A)[0]

The algorithm is incorrect. For this input A = [7, 3, 20, 16, 5, 8] it returns 6. The correct answer is 7 (7, 3),(7, 5),(20, 16),(20, 5),(20, 8),(16, 5),(16, 8). For some inputs the answer is correct. I am not sure what causes it.

I wish I knew for what inputs it gives a correct result. You have a typo: len(A) - 1 should be len(A) - i .

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