Skip to content

Instantly share code, notes, and snippets.

@EDmitry
Created March 17, 2015 19:06
Show Gist options
  • Save EDmitry/9c3b07c53e32feee4d2f to your computer and use it in GitHub Desktop.
Save EDmitry/9c3b07c53e32feee4d2f to your computer and use it in GitHub Desktop.
extract minimum from the list in O(N)
extractMinBy :: (a -> a -> Ordering) -> [a] -> (a, [a])
extractMinBy f (x:xs) = extractMinBy' f [x] xs (x, xs)
extractMinBy' :: (a -> a -> Ordering) -> [a] -> [a] -> (a, [a]) -> (a, [a])
extractMinBy' f left [] r = r
extractMinBy' f left (r:right) z@(x, xs) = extractMinBy' f (left ++ [r]) right newResult
where newResult = if f r x == LT then (r, left ++ right) else z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment