summaryrefslogtreecommitdiff
path: root/sort/gnomesort.hs
blob: 2a9b9ce71e97dfff88a9c8d32610a987262aa7e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19



gnomeSort :: Ord a => [a] -> [a]
gnomeSort list = doGnomeSort list 1



doGnomeSort :: Ord a => [a] -> Int -> [a]
doGnomeSort list pos | pos >= length list = list
doGnomeSort list pos =
    if (list !! pos) >= (list !! (pos - 1))
        then doGnomeSort list (pos + 1)
        else let list' = (take (pos - 1) list) ++ [list !! pos] ++
                         [list !! (pos - 1)] ++ (drop (pos + 1) list)
                 pos' = if pos > 1 then pos - 1 else pos
             in doGnomeSort list' pos'