Luis Dos Reis
Luis Dos Reis

Reputation: 393

Sorting algorithm in Haskell

I am trying to implement a very trivial sorting algorithm in Haskell. It compiles but keeps giving me incorrect outputs.

Here is the code

import Data.List

minimum' :: (Ord a) => [a] -> a
minimum' (x:xs) = foldr (\ x y -> if x <= y then x else y) x xs

qsrt :: (Ord a) => [a] -> [a]
qsrt [] = []
qsrt l@(x:xs) = minimum' l : qsrt xs

Any thoughts?

Upvotes: 1

Views: 889

Answers (2)

Luis Dos Reis
Luis Dos Reis

Reputation: 393

Just as an addendum to Rein Henrichs's answer, I managed to craft a correct version of the above using a filter.

import Data.List

minimum' :: (Ord a) => [a] -> a
minimum' (x:xs) = foldl' (\ x y -> if x <= y then x else y) x xs

srt :: (Ord a) => [a] -> [a]
srt [] = []
srt l = ml : srt (delete ml l)
    where ml = minimum' l

Upvotes: 1

Rein Henrichs
Rein Henrichs

Reputation: 15605

The logic error is that qsrt takes the minimum element of l and then skips x, but x would only be the minimum element of l by accident so you're usually skipping the wrong element.

Upvotes: 6

Related Questions