[英]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.