Skip to content

Instantly share code, notes, and snippets.

@mather
Last active April 27, 2016 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mather/6521d428ff90068d553b637f3d690763 to your computer and use it in GitHub Desktop.
Save mather/6521d428ff90068d553b637f3d690763 to your computer and use it in GitHub Desktop.
バブルソート in Haskell
module BubbleSort where
-- |
-- Bubble Sort
--
-- >>> bubbleSort [1,2,3]
-- [1,2,3]
--
-- >>> bubbleSort [2,3,1]
-- [1,2,3]
--
-- >>> bubbleSort [3,2,1]
-- [1,2,3]
bubbleSort :: Ord a => [a] -> [a]
bubbleSort [] = []
bubbleSort xs = y : (bubbleSort ys)
where y:ys = swapList xs
-- |
-- Swap List Items
--
-- >>> swapList [1,2,3]
-- [1,2,3]
--
-- >>> swapList [2,3,1]
-- [1,2,3]
--
-- >>> swapList [3,2,1]
-- [1,3,2]
swapList :: Ord a => [a] -> [a]
swapList [] = []
swapList (x:[]) = x:[]
swapList (x:xs)
| x > y = y : x : ys
| otherwise = x : y : ys
where y:ys = swapList xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment