Mergesort Inversion Count Typed
Count inversions in a number array using a typed mergesort that counts crossings during the merge step.
Code
function countInversions(arr: number[]): number {
const tmp: number[] = new Array(arr.length);
function merge(lo: number, mid: number, hi: number): number {
let i = lo, j = mid, k = lo, inv = 0;
for (let x = lo; x <= hi; x++) tmp[x] = arr[x];
while (i < mid && j <= hi) {
if (tmp[i] <= tmp[j]) arr[k++] = tmp[i++];
else { arr[k++] = tmp[j++]; inv += mid - i; }
}
while (i < mid) arr[k++] = tmp[i++];
while (j <= hi) arr[k++] = tmp[j++];
return inv;
}
function sort(lo: number, hi: number): number {
if (lo >= hi) return 0;
const mid = (lo + hi + 1) >>> 1;
return sort(lo, mid - 1) + sort(mid, hi) + merge(lo, mid, hi);
}
return sort(0, arr.length - 1);
}Inside the snippet
Count the functions mid, countInversions, merge and sort as the entire surface area of Mergesort Inversion Count Typed.
The core work runs in nested loops — outer for (let x = lo; x <= hi; x++) tmp[x] = arr[x];, inner while (i < mid && j <= hi).
Watch out for
- The guard
lo >= hishort-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
The main signature reads const mid = (lo + hi + 1)
Core lines
return sort(lo, mid - 1) + sort(mid, hi) + merge(lo, mid, hi);
else { arr[k++] = tmp[j++]; inv += mid - i; }
return sort(0, arr.length - 1);
Interactive Tools for This Topic
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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `mid`, `countInversions`, `merge` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.