Help us understand the problem. What is going on with this article?

Haskellでクイックソートとマージソート

More than 1 year has passed since last update.

最近Haskellを勉強し始めたのでアウトプットのためクイックソートとマージソートを書いてみた。

クイックソート

quickSort [] = []
quickSort [x] = [x]
quickSort (x:xs) = quickSort left ++ [x] ++ quickSort right
    where left  = filter (<  x) xs
          right = filter (>= x) xs

main = do
    print $ quickSort [1, 8, 7, 6, 2, 5, 9, 4, 0, 3]

リストの先頭要素をピボットにしてピボットより小さい要素をleftにピボット以上の要素をrightに集めます。集めたleftrightにそれぞれ再帰的にソートを作用させます。

マージソート

merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys)
    | x < y     = x : merge xs (y:ys)
    | otherwise = y : merge (x:xs) ys

mergeSort []  = []
mergeSort [x] = [x]
mergeSort xs  = merge (mergeSort (left)) (mergeSort (right))
    where left  = take half xs
          right = drop half xs
          half  = length xs `div` 2

main = do
    print $ msort [1, 8, 7, 6, 2, 5, 9, 4, 0, 3]

ソートされた二つのリストから小さい順に値をとりだし、一つのリストにまとめ上げます。

結果

むちゃくちゃスッキリしてて書いてて気持ちいい...

参考文献

Haskell 超入門

ymmy02
sprocket
"Sprocket(スプロケット)は、Webサイトにおけるコンバージョン(購入・入会・資料請求・問合せ等)を増やしたい企業様向けに、自社開発のWeb接客ツールの導入及びコンバージョン改善コンサルティングを行っている会社です。 "
https://www.sprocket.bz/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした