簡體   English   中英

使用Mergesort計算C ++中的反轉數

[英]Using Mergesort to calculate number of inversions in C++

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。任何幫助或注釋都將不勝感激。 (甚至也批評!!)

從入門到算法的偽代碼(Cormen。MIT Press)第二版:

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

應該注意,實際上不需要計數的變量。 本質上,合並排序是一種固有的遞歸算法。 您的實現應嚴格遵循此偽代碼。 同時根據需要進行調整以適應您的需求。 但是在這種情況下。 實際上,這種偽代碼的直接實現將在經典合並排序期間計算倒數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM