Created
March 26, 2012 19:05
-
-
Save supki/2208761 to your computer and use it in GitHub Desktop.
Linear complexity selection algorithm (from Algo class at coursera).
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
module LinearSelection where | |
import System.Random (randomRIO) | |
import System.IO.Unsafe (unsafePerformIO) | |
select :: Ord a => [a] -> Int -> a | |
select [x] 1 = x | |
select xs n | |
| n > length xs || n <= 0 = error $ "select: wrong index (" ++ show n ++ ") where length is " ++ show (length xs) | |
| length ls < n = select bs (n - length ls) | |
| otherwise = select ls n | |
where (ls, bs) = partition xs | |
partition :: Ord a => [a] -> ([a], [a]) | |
partition [] = ([], []) | |
partition xs = go ([], []) xs | |
where pivot = xs !! (unsafePerformIO $ randomRIO (0, length xs - 1)) | |
go (ls, bs) (y:ys) | |
| y > pivot = go (ls, y:bs) ys | |
| otherwise = go (y:ls, bs) ys | |
go ps [] = ps |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment