1

我正在尝试使用 MergeSort 从文件中计算反转,我的代码似乎适用于较小的文件,但较大的文件会产生错误的输出。我的代码:

反转计数.py:

count = 0

def merge_sort_inversions(numberlist):
    if len(numberlist) < 2:
        return numberlist
    else:
        mid = len(numberlist) // 2
        lefthalf = numberlist[:mid]
        righthalf = numberlist[mid:]

    return sort_count_inversions(merge_sort_inversions(lefthalf), merge_sort_inversions(righthalf))

def sort_count_inversions(l, r):
    result = []

    i=0
    j=0

    global count

    while(i < len(l) and j<len(r)):
        if (r[j] > l[i]):
            result.append(l[i])
            i+= 1
        elif(r[j] < l[i]):
            result.append(r[j])
            count += (len(l) - i)
            j+=1
    if(j>=len(r)):
        result+=l
    elif(i>=len(l)):
        result+=r

    print(count)
    return result

应用程序.py:

import InversionCount

text_file = open('algorithms-1-test2.txt', 'r')
number_list = text_file.readlines()
number_list = list(map(int, number_list))

InversionCount.merge_sort_inversions(number_list)

答案是:2407905288,但我得到的最终打印计数是:22945388587258。我非常感谢任何帮助,因为我正在尝试自己学习算法。另外,我的问题发生在大文件上,那么我将如何调试似乎只有在输入非常大时才会出现的问题(我尝试用较小的输入对此进行测试,它给出了正确的答案)?谢谢!

4

0 回答 0