Skip to content

Instantly share code, notes, and snippets.

@purpleP
Created Sep 5, 2017
Embed
What would you like to do?
Efficient algorithm for finding minimum and maximum value from sequence
import Data.Tuple (swap)
import System.Environment (getArgs)
minmax (a:b:xs) = foldl (minmax') (sort' (a, b)) (pairs xs)
where minmax' (curmin, curmax) candidates = (newmin, newmax)
where (cmin, cmax) = sort' candidates
newmin = if cmin < curmin then cmin else curmin
newmax = if cmax > curmax then cmax else curmin
sort' tup@(a, b) = if a <= b then tup else swap tup
pairs :: [a] -> [(a, a)]
pairs (a:b:as) = (a, b):(pairs as)
pairs (c:[]) = (c, c):[]
pairs [] = []
main = do
args <- getArgs
let [from, till] = map read args :: [Int]
print $ minmax [from..till]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment