Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 合并排序在大数据集上不起作用_Python_Algorithm_Mergesort - Fatal编程技术网

Python 合并排序在大数据集上不起作用

Python 合并排序在大数据集上不起作用,python,algorithm,mergesort,Python,Algorithm,Mergesort,我尝试使用合并排序算法来计算数组中的倒数,该数组包含1到100000范围内的所有数字。当我输入一个小数据集时,它可以正常工作,但当我输入包含较大数组的文件时,它不会返回正确答案。我输入文件的方式有问题吗?我以前从未将文件输入到数组中,因此我无法确定是否正确 file = open('IntegerArray.txt','r') integerArray = [] for line in file: integerArray.append(line) inversions = 0 d

我尝试使用合并排序算法来计算数组中的倒数,该数组包含1到100000范围内的所有数字。当我输入一个小数据集时,它可以正常工作,但当我输入包含较大数组的文件时,它不会返回正确答案。我输入文件的方式有问题吗?我以前从未将文件输入到数组中,因此我无法确定是否正确

file = open('IntegerArray.txt','r')
integerArray = []
for line in file:
    integerArray.append(line)


inversions = 0

def divide(list):
    if len(list) > 1:
        middle = int(len(list) / 2)
        left = divide(list[:middle])
        right = divide(list[middle:])

        #left = divide(left)
        #right = divide(right)

    elif len(list) <= 1:
        return list

    return merge(left,right)

def merge(left,right):
    global inversions
    result = []

    while left != [] and right != []:
        if left[0] < right[0]:
            result.append(left[0])
            if len(left) > 1:
                left = left[1:]
            else:
                left = []
        elif left[0] > right[0]:
            result.append(right[0])
            inversions += len(left)
            if len(right) > 1:
                right = right[1:]
            else:
                right = []

    if left != []:
        result += left
    if right != []:
        result += right

    return result

divide(integerArray)
print(inversions)
file=open('IntegerArray.txt','r')
整数数组=[]
对于文件中的行:
integerArray.append(行)
反演=0
定义划分(列表):
如果len(列表)>1:
中间=整数(长(列表)/2)
左=除(列表[:中间])
右=除(列表[中间:)
#左=除(左)
#右=除(右)
elif len(列表)1:
左=左[1:]
其他:
左=[]
elif左[0]>右[0]:
result.append(右[0])
反转+=len(左)
如果len(右)>1:
右=右[1:]
其他:
右=[]
如果离开!=[]:
结果+=左
如果正确的话!=[]:
结果+=正确
返回结果
除法(整数数组)
打印(反转)

这应该返回2407905288,但返回2397819672。

尝试k路合并排序。大型数据集的问题在于,简单的合并排序必须在运行时将两个大型数组放入主内存,这有时是不可能的。

似乎它不适用于大多数数字大于9的情况!您将数字保存在字符串列表中。因此,合并函数中的比较器比较两个字符串,因此示例2大于12

至少您需要将第一行更改为:

file = open('IntegerArray.txt','r')
integerArray = []
for line in file.readlines():
    integerArray.append(int(line.strip()))

正如MostafaR所指出的,
integerArray
包含字符串,这充其量也显得有些奇怪。我将添加另外两个注释,可能与您正在处理的内容无关:您不处理等值元素,也不在两个子列表上递归(这两个子列表都是真正的合并排序所需要的)。那么它不是递归的呢?是因为实施,还是我还没有接近?我不是在正确的位置调用除法函数吗?哦,糟糕,不是,只是在快速扫描代码时误读了代码。(可能是因为注释掉的部分,我猜您以前会执行两个单独的步骤。)