Skip to content

Instantly share code, notes, and snippets.

@mchav
Created June 17, 2016 18: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 mchav/41f598a9ec5141262889317febbbd0e0 to your computer and use it in GitHub Desktop.
Save mchav/41f598a9ec5141262889317febbbd0e0 to your computer and use it in GitHub Desktop.
import Control.Monad
import Data.Vector hiding (map)
import Prelude hiding (head, tail, length, splitAt)
import System.IO
inversions :: Vector Int -> Int
inversions = snd . countInversions
countInversions :: Vector Int -> (Vector Int, Int)
countInversions xs
| length xs <= 1 = (xs, 0)
| otherwise = let mid = (length xs) `div` 2
(left, right) = splitAt mid xs
(left' , l) = countInversions $! left
(right' , r) = countInversions $! right
(whole , w) = id $! countSplit left' right'
in (whole, l + r + w)
countSplit :: Vector Int-> Vector Int -> (Vector Int, Int)
countSplit xs ys
| length xs == 0 = (ys, 0)
| length ys == 0 = (xs, 0)
| x <= y = (cons x left , l)
| otherwise = (cons y right, r + length xs)
where (left, l) = countSplit (tail xs) ys
(right, r) = countSplit xs (tail ys)
x = head xs
y = head ys
main = do
withFile "IntegerArray.txt" ReadMode $ \h -> liftM (fromList . map (read :: String -> Int) . lines) (hGetContents h) >>= (print . inversions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment