Search code examples
haskellselection-sort

functional non-tail recursive version of selection sort in Haskell


I am looking for the non-tail recursive version of the following selection sort code in Haskell:

import Data.List (minimum, delete)

ssort :: Ord t => [t] -> [t]
ssort [] = []
ssort xs = let { x = minimum xs } in  x : ssort (delete x xs)

Can you please provide with a non-tail recursive version of selection sort?

I know it is not a good idea to change the original code but I need that version to proceed with an experiment.


Solution

  • The code presented is not tail-recursive since you invoke the : cons function. All the recursive calls will be held on the memory stack waiting for the evaluation of ssort (delete x xs) to finish. A tail-recursive version could look like this:

    import Data.List (minimum, delete)
    
    ssort :: Ord t => [t] -> [t] -> [t]
    ssort [] acc = reverse acc
    ssort xs acc = let { x = minimum xs } in ssort (delete x xs) (x : acc)