Created
April 16, 2014 08:40
-
-
Save mlhaufe/10833981 to your computer and use it in GitHub Desktop.
Count inversions in an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bugged: [4,5,6,1,2,3]