Created
February 1, 2013 10:58
-
-
Save dschobel/4690653 to your computer and use it in GitHub Desktop.
counting inversions in sml in O(n*log(n)) time
This file contains 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
fun count_and_sort [] = ([],0) | |
| count_and_sort [x] = ([x],0) | |
| count_and_sort xs = | |
let | |
fun count_and_sort_split_inversions([],ys,acc,sum) = (List.rev(acc) @ ys,sum) | |
| count_and_sort_split_inversions(xs,[],acc,sum) = (List.rev(acc) @ xs,sum) | |
| count_and_sort_split_inversions(x :: xs, y :: ys,acc,sum) = | |
if x < y | |
then count_and_sort_split_inversions(xs, y :: ys, x :: acc, sum) | |
else count_and_sort_split_inversions(x :: xs, ys, y :: acc, sum + List.length(x :: xs)) | |
val len = List.length xs | |
val (left,right) = splitAt(xs,len div 2) | |
val (a,x) = count_and_sort left | |
val (b,y) = count_and_sort right | |
val (c,z) = count_and_sort_split_inversions (left,right,[],0) | |
in | |
(c, x + y + z) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment