Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion Haskell

I am trying to implement something like this:

mymin (x:[]) = x
mymin (x:y:xs) = mymin ((if x < y then x else y):xs)

mysort [] = []
mysort (x) = mymin x (mysort othervalues)

i know this code is wrong but its just the idea. How can i concat the rest of values with the min value that return the recursion. input will be like

mysort [7,9,3,7,1,2]

[1,**7,9,3,7,2**]
[1,2,**7,9,3,7**]
[1,2,3,**7,9,7**]
[1,2,3,7,**7,9**]
[1,2,3,7,7,**9**]
[1,2,3,7,7,9]
like image 950
Urah Avatar asked Feb 03 '26 06:02

Urah


1 Answers

I think you are trying to implement selection sort.

It is better for mymin to return the minimum element along with rest of the elements of the list.

mymin :: Ord a => [a] -> (a,[a])
mymin [x] = (x,[])
mymin (x:xs) = let (min,rest) = mymin xs
    in if x < min then (x,min:rest) else (min,x:rest)

mysort :: Ord a => [a] -> [a]
mysort [] = []
mysort xs = let (min,rest) = mymin xs
    in min:mysort rest
like image 171
Satvik Avatar answered Feb 06 '26 03:02

Satvik