Jump to content

Sorting algorithms/Bubble sort: Difference between revisions

added Haskell
m (→‎[[Ada]]: Add generic function parameter "=")
(added Haskell)
Line 105:
std::cout << std::endl ;
}
 
==[[Haskell]]==
[[Category:Haskell]]
This version checks for changes in a separate step for simplicity, because Haskell has no variables to track them with.
bsort :: Ord a => [a] -> [a]
bsort s = case _bsort s of
t | t == s -> t
| otherwise -> bsort t
where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs))
| otherwise = x:(_bsort (x2:xs))
_bsort s = s
This version uses the polymorphic <tt>Maybe</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>Ord a => [a] -> Maybe [a]</tt>.) It is slightly faster than the previous one.
bsort :: Ord a => [a] -> [a]
bsort s = case _bsort s of
Nothing -> s
Just s2 -> bsort s2
where _bsort (x:x2:xs) | x > x2 = case _bsort (x:xs) of
Nothing -> Just $ x2:x:xs
Just xs2 -> Just $ x2:xs2
| otherwise = case _bsort (x2:xs) of
Nothing -> Nothing
Just xs2 -> Just $ x:xs2
_bsort _ = Nothing
 
==[[Perl]]==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.