3

我正在尝试实现这样的事情:

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

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

我知道这段代码是错误的,但这只是想法。如何将其余值与返回递归的最小值连接起来。输入会像

我的排序 [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]
4

3 回答 3

6

我认为您正在尝试实现选择排序。

最好mymin将最小元素与列表的其余元素一起返回。

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
于 2012-12-10T08:55:17.120 回答
2

您需要从列表中删除第一次出现的 min 并将其连接到其余部分的前面

mymin :: (Ord a) => [a] -> a
mymin [x] = x 
mymin (x:y:xs) | x < y     = mymin (x:xs)
               | otherwise = mymin (y:xs)

myremove :: (Eq a) => a -> [a] -> [a] 
myremove x []  = [] 
myremove x (y:ys) | x == y    = ys
                  | otherwise = y: myremove x ys 

mysort :: (Ord a) => [a] -> [a] 
mysort []  = [] 
mysort [x] = [x] 
mysort xs  = x : mysort (myremove x xs) where x = mymin xs
于 2012-12-10T09:48:05.510 回答
0

基于 Satvik 的回答,您可以通过编写mymin为避免显式递归

mymin :: Ord a => [a] -> (a, [a])
mymin (x : xs) = foldr f (x, []) xs where
  f z (y, ys) = if y < z then (y, z : ys) else (z, y : ys)        
于 2012-12-11T07:53:07.820 回答