Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Created April 16, 2014 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlhaufe/10833981 to your computer and use it in GitHub Desktop.
Save mlhaufe/10833981 to your computer and use it in GitHub Desktop.
Count inversions in an array
function countInversions(xs){
var count = 0;
function mergeSort(xs){
var size = xs.length
if (size < 2) return xs
var mid = Math.floor(size / 2),
left = xs.slice(0, mid),
right = xs.slice(mid)
return merge(mergeSort(left), mergeSort(right))
}
function merge(left, right){
var result = [];
while (left.length && right.length) {
if(left[0] <= right[0]) {
result.push(left.shift())
} else {
count++
result.push(right.shift())
}
}
while (left.length)
result.push(left.shift())
while (right.length)
result.push(right.shift())
return result;
}
mergeSort(xs)
return count
}
var xs = [34, 203, 3, 746, 200, 984, 198, 764, 9]
countInversions(xs) //9
@mlhaufe
Copy link
Author

mlhaufe commented May 7, 2014

Bugged: [4,5,6,1,2,3]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment