反转计数问题MergeSort算法 - Python

时间:2016-06-28 15:52:26

标签: python algorithm mergesort inversion

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

InversionCount.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

Application.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。我真的很感激任何帮助,因为我试图自己学习算法。另外,我的问题发生在大文件中,所以我如何调试一个只有非常大的输入才会出现的问题(我尝试用较小的输入测试它并给出正确的答案)?谢谢!

0 个答案:

没有答案