Algorithm 反转计数算法
我刚刚实现了一个反转计数算法(计算出有多少个数字是无序的),其中按顺序应该表示按升序排序的数组Algorithm 反转计数算法,algorithm,sorting,mergesort,divide-and-conquer,Algorithm,Sorting,Mergesort,Divide And Conquer,我刚刚实现了一个反转计数算法(计算出有多少个数字是无序的),其中按顺序应该表示按升序排序的数组 Merge-and-Count(A,B): Maintain a Current pointer into each list, initialized to point to the front elements Maintain a variable Count for the number of inversions, initialized to 0 While bo
Merge-and-Count(A,B):
Maintain a Current pointer into each list, initialized to point to the front elements
Maintain a variable Count for the number of inversions, initialized to 0
While both lists are nonempty:
Let a_i and b_j be the elements pointed to by the Current pointer
Append the smaller of these two to the output list
If b_j is the smaller element then:
Increment Count by the number of elements remaining in A
Endif
Advance the Current pointer in the list from which the smaller element was selected.
EndWhile
Once one list is empty, append the remainder of the other list to the output
Return Count and the merged list
countInversions(L):
If the list has one element then:
return 0
Else
Divide the list into two halves:
A contains the first n/2 elements
B contains the remaining n/2 elements
(r_A, A) = countInversions(A)
(r_B, B) = countInversions(B)
(r, L) = Merge-and-Count(A,B)
Endif
Return r = r_A + r_B + r and the sorted list L
让我困惑的是最后一行返回
r\u A+r\u B+r
。我首先想到的是返回r
,因为这将给出列表中的倒数(A,B),这基本上就是我们需要的。为什么还要加上子列表的反转数,它们将包含在r中,不是吗?此外,这里有一个算法的例子:对于列表2,4,1,3,5,它将找到三个反演:(2,1),(4,1)和(4,3)。注:我遵循Jon Kleinberg的《算法设计书》第222页的解释。我有点搞砸了缩进,但倒计时是另一个功能。r
是在合并a
和B
时计算的倒计时数,它们已经排序好了。只返回r
将丢失排序A
和B
时计算的反转。哦,真的!谢谢你,伙计。