1
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'인수의 효과에 대해 혼란스러워합니다. 내가 복사에 대한 그들에 대한 액세스 권한 및 병합, 그래서 내가 거기에서 그들을 필요하지만,Mergesort를 사용하여 C++에서 역변환 횟수를 계산하십시오.
여기 모호성을 끼쳐 드려 죄송합니다. 그 배열에 대한 올바른 결과 아니며, 내 계산으로는 역전이 어떤 도움이나 의견이 크게 감상 할 수있다 (16)와 같아야 분명히
Input (A)= 4 2 53 8 1 19 21 6
19
19
21
19
21
19
21
6
inversions=9
: 여기에 출력됩니다. (심지어 비판도;!)
미래에는 ctrl-k로 코드 블록을 포맷 할 수 있으므로 실제로 읽을 수 있습니다. – Joe
그래, 난 그냥 형식 도움말, 고마워 보았다. 그렇게하면 모든 줄을 오른쪽으로 4 칸씩 이동하는 것보다 훨씬 쉬울 것입니다 :/ – Brown
그리고 질문이 ....? –