Skip to content

Instantly share code, notes, and snippets.

@theburningmonk
Created February 5, 2013 23:39
Show Gist options
  • Select an option

  • Save theburningmonk/4718771 to your computer and use it in GitHub Desktop.

Select an option

Save theburningmonk/4718771 to your computer and use it in GitHub Desktop.
Algorithm to count the number of inversions in an array
let countSplitInv (l : 'a array) (r : 'a array) n =
let res = Array.zeroCreate<'a> n
let ln = l.Length
let mutable i, j, inv = 0, 0, 0
for k = 0 to n-1 do
if i >= ln then res.[k] <- r.[j]; j <- j + 1
elif j >= r.Length then res.[k] <- l.[i]; i <- i + 1
elif l.[i] < r.[j] then res.[k] <- l.[i]; i <- i + 1
else res.[k] <- r.[j]; j <- j + 1; inv <- inv + ln - i
res, inv
let rec sortAndCount (arr : 'a array) =
match arr.Length with
| 0 | 1 -> arr, 0
| n -> let (b, x) = sortAndCount(arr.[0..n/2-1])
let (c, y) = sortAndCount(arr.[n/2..n-1])
let (d, z) = countSplitInv b c n
d, x + y + z
let countInversion arr = snd <| sortAndCount arr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment