Mergesort Inversion Count (JavaScript)
Count the number of inversions in an array using a modified mergesort that counts crossings during the merge step in O(n log n) time.
Code
function countInversions(arr) {
const tmp = new Array(arr.length);
function merge(lo, mid, hi) {
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, hi) {
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);
}What the code does
Count the functions mid, countInversions, merge and sort as the entire surface area of Mergesort Inversion Count (JavaScript).
The structure is a loop within a loop: for (let x = lo; x <= hi; x++) tmp[x] = arr[x]; outside, while (i < mid && j <= hi) inside.
What to watch for
- The guard
lo >= hishort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The primary signature is const mid = (lo + hi + 1)
Statements that matter
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
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `mid`, `countInversions`, `merge` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.