Skip to content

Instantly share code, notes, and snippets.

@dschobel
Created February 1, 2013 10:58
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 dschobel/4690653 to your computer and use it in GitHub Desktop.
Save dschobel/4690653 to your computer and use it in GitHub Desktop.
counting inversions in sml in O(n*log(n)) time
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