我一直在试着为倒数写一个伪代码。
在这个例子中,我们的数组被称为长度n的主数组,并且假设n是偶数整数。
根据我的理解,当i<j, mainArray[i] > mainArray[j]时需要在数组中进行反转然后我们交换位置来排序。
使用合并排序算法,当我们到达基本情况并开始合并两个半部分(左半部分和右半部分)时,代码如下所示

let i = 0, j=0, k=0, inversions = 0
for k in range(0,n-1)
    if left-half[i] < right-half[j]
       mainArray[k] = left-half[i]
       i+=1
    else
       mainArray[k] = right-half[j]
       j+=1

       //now at this point an inversion has occurred
       //so from my understanding at this point there was only 1 swap? because the program
       //skipped left-half[i] and proceeded to right-half[j]
       // so my answer was **"Inversions = Inversions + 1"** incrementing by 1 Inversions wherever the **Else-Block is run**.


       //but in the solution the correct answer is
       Inversions = Inversions + {(n/2)-i}

我不明白这个部分为什么假设右半部分[j]与数组左半部分的所有剩余元素交换位置。我遗漏了什么要点?
任何帮助都将不胜感激谢谢。

最佳答案

回想一下left-halfright-half是排序的,所以如果i<j, left-half[i] > right-half[j]这也意味着left-half[i+1..n/2] > right[j]。所以我们计算所有的倒数,而不仅仅是一个倒数。

10-07 16:28