Using Mergesort to calculate number of inversions in C++

拥有回忆 提交于 2019-12-06 16:04:38

Psuedo-code from Intro to Algorithms (Cormen. MIT Press) 2nd Edition:

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

One should note that the counted variable is actually not needed. Merge sort is an inherently recursive algorithm by nature. Your implementation should closely follow this psuedo-code. While adapting where necessary to suit your needs. However in this case. A direct implementation of this psuedo-code will in fact count inversions during a classic merge sort.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!