比較の仕方がデータによらないソートである Bitonic Sort を Haskell で書いてみた.要素数 2^n 限定.だけ.
import System.Random randInt :: IO (Int) randInt = getStdRandom (randomR (0,1000)) randInts n = randInts' n [] where randInts' n xs = if n == 0 then return xs else randInt >>= (\x -> randInts' (n-1) (x:xs)) bimerge xs ys 1 dir = unzip (zipWith (\x y -> if (x < y) == dir then (x,y) else (y,x)) xs ys) bimerge xs ys n dir = (xxs++xys, yxs++yys) where (xs', ys') = unzip (zipWith (\x y -> if (x < y) == dir then (x,y) else (y,x)) xs ys) n2 = (n `div` 2) (xxs, xys) = bimerge (take n2 xs') (drop n2 xs') n2 dir (yxs, yys) = bimerge (take n2 ys') (drop n2 ys') n2 dir bisort xs = bisort' xs (length xs) True where bisort' zs 1 dir = zs bisort' zs n dir = xs'' ++ ys'' where n2 = (n `div` 2) xs' = bisort' (take n2 zs) n2 dir ys' = bisort' (drop n2 zs) n2 (not dir) (xs'', ys'') = bimerge xs' ys' n2 dir -- randInts 1024 >>= (\x -> print (bisort x)) -- randInts 1024 >>= (\xs -> print (snd (foldl (\(x, f) y -> (y, and [f, (x <= y)])) (-1, True) (bisort xs))))
- Newer: AWK - はじめ