void MergeSort(int A[], int n, int B[], int C[])
{
if(n > 1)
{
Copy(A,0,floor(n/2),B,0,floor(n/2));
Copy(A,floor(n/2),n-1,C,0,floor(n/2)-1);
MergeSort(B,floor(n/2),B,C);
MergeSort(C,floor(n/2),B,C);
Merge(A,B,0,floor(n/2),C,0,floor(n/2)-1);
}
};
void Copy(int A[], int startIndexA, int endIndexA, int B[], int startIndexB, int endIndexB)
{
while(startIndexA < endIndexA && startIndexB < endIndexB)
{
B[startIndexB]=A[startIndexA];
startIndexA++;
startIndexB++;
}
};
void Merge(int A[], int B[],int leftp, int rightp, int C[], int leftq, int rightq)
//Here each sub array (B and C) have both left and right indices variables (B is an array with p elements and C is an element with q elements)
{
int i=0;
int j=0;
int k=0;
while(i < rightp && j < rightq)
{
if(B[i] <=C[j])
{
A[k]=B[i];
i++;
}
else
{
A[k]=C[j];
j++;
inversions+=(rightp-leftp); //when placing an element from the right array, the number of inversions is the number of elements still in the left sub array.
}
k++;
}
if(i=rightp)
Copy(A,k,rightp+rightq,C,j,rightq);
else
Copy(A,k,rightp+rightq,B,i,rightp);
}
我特别对MergeSort调用中第二个'B'和'C'参数的影响感到困惑。我需要它们,所以我可以访问它们进行复制和合并,但是
我为这里的含糊不清道歉。这是输出:
Input (A)= 4 2 53 8 1 19 21 6
19
19
21
19
21
19
21
6
inversions=9
显然,这不是数组的正确结果,而且根据我的统计,反转应该等于16.任何帮助或评论都将非常感激。 (甚至批评!;)
答案 0 :(得分:1)
Intro to Algorithms的Psuedo-code(Cormen.MIT出版社)第2版:
MERGE -INVERSIONS ( A, p, q, r)
n1 ← q − p + 1
n2 ← r − q
create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
for i ← 1 to n1
do L[i] ← A[ p + i − 1]
for j ← 1 to n2
do R[ j ] ← A[q + j ]
L[n 1 + 1] ← ∞
R[n 2 + 1] ← ∞
i ←1
j ←1
inversions ← 0
counted ← FALSE
for k ← p to r
do
if counted = FALSE and R[ j ] < L[i]
then inversions ← inversions +n1 − i + 1
counted ← TRUE
if L[i] ≤ R[ j ]
then A[k] ← L[i]
i ←i +1
else A[k] ← R[ j ]
j ← j +1
counted ← FALSE
return inversions
应该注意到实际上不需要计算的变量。合并排序本质上是一种固有的递归算法。您的实现应该严格遵循此伪代码。在适当的时候根据您的需求进行调整。但是在这种情况下。直接实现此伪代码实际上会在经典合并排序期间计算反转。