繁体   English   中英

计算数组中的反转次数(python代码)

[英]Count number of inversions in an array (python code)

所以我正在阅读这段代码,它正在浏览一个包含 10,000 个随机顺序(无重复)的整数的文件,并计算反转的次数。 我没有完全理解这段代码,我有几个问题:首先我想这是不断地将数组分成左右,直到长度为 1。当左数组和右数组的长度都为 1 时,我们该怎么办?在这里算吗?(我可能完全误解了这段代码,请纠正我)。 “中段”元素 go 每次都在哪里? 从我每次看到的情况来看,这个元素既不属于右数组也不属于左数组。 最后一个问题是,“count += (len(a)-i)”行只有在左右数组都已经排序(排序)时才是正确的,但我看不到这个排序过程在哪里。 这是代码:

from pathlib import Path
file_path = Path("c:/Users/Lyra/Desktop/Algorithm/")

inFile = open(file_path / "IntegerArray.txt", 'r')

with inFile as f:
    numList = [int(integers.strip()) for integers in f.readlines()]
    
count = 0

def inversionsCount(x):
    global count
    midsection = len(x) // 2
    leftArray = x[:midsection]
    rightArray = x[midsection:]
    if len(x) > 1:
        # Divid and conquer with recursive calls
        # to left and right arrays similar to
        # merge sort algorithm
        inversionsCount(leftArray)
        inversionsCount(rightArray)
        
        # Merge sorted sub-arrays and keep
        # count of split inversions
        i, j = 0, 0
        a = leftArray; b = rightArray
        for k in range(len(a) + len(b) + 1):
            if a[i] <= b[j]:
                x[k] = a[i]
                i += 1
                if i == len(a) and j != len(b):
                    while j != len(b):
                        k +=1
                        x[k] = b[j]
                        j += 1
                    break
            elif a[i] > b[j]:
                x[k] = b[j]
                count += (len(a) - i)
                j += 1
                if j == len(b) and i != len(a):
                    while i != len(a):
                        k+= 1
                        x[k] = a[i]
                        i += 1                    
                    break   
    return x
# call function and output number of inversions
inversionsCount(numList)
print (count)

我知道我问了很多问题,但我现在真的很困惑,提前谢谢!

没有“中段”元素。 midsection只是x leftArray = x[:midsection] 和 rightArray = x[midsection:] 中间的索引,将一起复制 x 中的所有元素,如果长度为奇数,则中间元素将在rightArray中结束。

排序由 function 本身通过更改传递的参数x中的元素进行。 列表是可变的,并作为参考传递给 function。 所以每个x[n] = something都会影响传递的列表参数,因此也会影响调用 scope 中的相应变量。 这意味着在inversionsCount(leftArray) leftArray 被排序之后。

如果您运行一个较小的列表,例如inversionsCount([6,0,3,1,2,5,4])并在代码中放入一些print(interesting_varable) 然后你可能会发现发生了什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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