Mergesort Inversion Count (Go)
Count inversions in a slice using a modified Go mergesort that counts crossings during the merge step.
Code
package main
func countInversions(arr []int) int {
tmp := make([]int, len(arr))
var merge func(lo, mid, hi int) int
var sort func(lo, hi int) int
merge = func(lo, mid, hi int) int {
i, j, k, inv := lo, mid, lo, 0
for x := lo; x <= hi; x++ { tmp[x] = arr[x] }
for i < mid && j <= hi {
if tmp[i] <= tmp[j] { arr[k] = tmp[i]; i++ } else { arr[k] = tmp[j]; j++; inv += mid - i }
k++
}
for i < mid { arr[k] = tmp[i]; i++; k++ }
for j <= hi { arr[k] = tmp[j]; j++; k++ }
return inv
}
sort = func(lo, hi int) int {
if lo >= hi { return 0 }
mid := (lo + hi + 1) / 2
return sort(lo, mid-1) + sort(mid, hi) + merge(lo, mid, hi)
}
return sort(0, len(arr)-1)
}Counting inversions during the merge
Mergesort Inversion Count (Go) keeps everything in the function countInversions.
Repetition is confined to for x := lo; x <= hi; x++ { tmp[x] = arr[x] } — the rest of the file is straight-line.
Applying it
Entry signature: func countInversions(arr []int) int
Statements that matter
if tmp[i] <= tmp[j] { arr[k] = tmp[i]; i++ } else { arr[k] = tmp[j]; j++; inv += mid - i }
if lo >= hi { return 0 }
return sort(lo, mid-1) + sort(mid, hi) + merge(lo, mid, hi)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `countInversions` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.