Selection sort (Haskell)

From LiteratePrograms

Jump to: navigation, search
Other implementations: C | C++ | C# | Erlang | Haskell | Java | Python, arrays

This program is a code dump.
Code dumps are articles with little or no documentation or rearrangement of code. Please help to turn it into a literate program. Also make sure that the source of this code does consent to release it under the MIT or public domain license.

Calculating the minimum of a list

This function calculates the minimum value in a list.

<<ssort.hs>>=
min1:: (a->a->Bool)->[a]->a
min1 (<=) [] = undefined
min1 (<=) [x] = x
min1 (<=) (x:xs)
  | x <= (min1 (<=) xs) = x
  | otherwise = min1 (<=) xs  

Removing an element from a list

This function returns a list with the first occurrence of a given element removed.

<<ssort.hs>>=
delete:: (Eq a) => a->[a]->[a]
delete a [] = []
delete a (x:xs)
  | a==x = xs
  | otherwise = x:(delete a xs)

The actual sorting algorithm

This function implements the actual selection sort.

<<ssort.hs>>=
ssort:: (Eq a) => (a->a->Bool)->[a]->[a]
ssort (<=) [] = []
ssort (<=) xs = [x] ++ ssort (<=) (delete x xs) where x = min1 (<=) xs
Download code
Views