Created
October 21, 2012 04:59
-
-
Save msysyamamoto/3925887 to your computer and use it in GitHub Desktop.
comb sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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