Skip to content

Instantly share code, notes, and snippets.

@msysyamamoto
Created October 21, 2012 04:59
Show Gist options
  • Save msysyamamoto/3925887 to your computer and use it in GitHub Desktop.
Save msysyamamoto/3925887 to your computer and use it in GitHub Desktop.
comb sort
import Data.List
import Test.QuickCheck
combSort :: Ord a => [a] -> [a]
combSort xs = comb (gap (length xs)) xs
comb :: Ord a => Int -> [a] -> [a]
comb h xs
| h <= 0 = xs
| h == 1 = let sorted = comb' in
if xs == sorted
then sorted
else comb h sorted
| otherwise = comb (gap h) comb'
where
comb' = foldl (foldfunc h) xs [0..end xs h]
foldfunc g ys i
| ys !! i > ys !! (i + g) = swap i (i + g) ys
| otherwise = ys
end ys g = (length ys - 1) - g
gap :: Int -> Int
gap x = truncate $ fromIntegral x * 10 / 13
swap :: Int -> Int -> [a] -> [a]
swap i j xs = zipWith swap' [0..] xs
where
swap' n val
| n == i = xs !! j
| n == j = xs !! i
| otherwise = val
prop_combSort :: [Int] -> Bool
prop_combSort xs = combSort xs == sort xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment