Skip to content

Instantly share code, notes, and snippets.

@kagamilove0707
Created May 18, 2013 00:39
Show Gist options
  • Save kagamilove0707/5602788 to your computer and use it in GitHub Desktop.
Save kagamilove0707/5602788 to your computer and use it in GitHub Desktop.
ちょまどさんに触発されてHaskellでいくつかのソートアルゴリズムを書いてみました。
module Sort (
bubbleSort,
mergeSort,
quickSort) where
import Data.List (splitAt)
bubbleSort, mergeSort, quickSort :: Ord a => [a] -> [a]
bubbleSort xs = foldr ((.) bubbleSort' . flip const) xs [0..length xs]
where
bubbleSort' [] = []
bubbleSort' (x:[]) = [x]
bubbleSort' (x:y:xs)
|x > y' = y' : x : xs'
|otherwise = x : y' : xs'
where
(y':xs') = bubbleSort' (y:xs)
mergeSort [] = []
mergeSort [x] = [x]
mergeSort xs = case split xs of
(xs', ys') -> merge (mergeSort xs') (mergeSort ys')
where
merge xs [] = xs
merge[] ys = ys
merge (x:xs) (y:ys)
|x == y = x : y : merge xs ys
|x < y = x : merge xs (y:ys)
|x > y = y : merge (x:xs) ys
split xs = splitAt (length xs `div` 2) xs
quickSort [] = []
quickSort (x:xs) = quickSort [y|y <- xs, y < x] ++ [x] ++ quickSort [z|z <- xs, x <= z]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment