Quicksort算法仅适用于小数字的列表。为什么?

时间:2018-05-04 15:05:39

标签: haskell quicksort

我添加了两个帮助功能来拆分列表和添加tupples。 输出有两个不同的列表作为输入显示我的问题。

*主>快速排序[367,324,675,238,1237,345,12,45,1,434,2,1,33,43] [1,1,2,12,33,43,45,238,324,345,367,434,675,1237] - 有效

*主>快速排序[3687,324,675,238,1237,345,12,45,1,434,2,1,33,43] [3687,324,675,238,1237,345,12,45,1,434,2,1,33,43] - 不起作用

下面是代码:

    splitBy :: Int -> [Int] -> ([Int],[Int])

    splitBy n y = ([x|x <- y,x > n],[x|x <- y, x<=n]) 
    addi :: ([a],[a]) -> ([a],[a]) -> ([a],[a])
    addi ([],[]) ([],[]) = ([],[])
    addi (x,y) (w,z) =  (x++w,y++z)

    splitBy' :: Int -> [Int] -> ([Int],[Int])

    splitBy' _ [] = ([],[])
    splitBy' n (y:ys) =  addi (q,d) (splitBy' n ys)
        where q = if y > n then [] else [y]
            d = if y <= n then [] else [y]
    addi' :: ([a],[a]) -> [a]
    addi' ([],[]) = []
    addi' (x,z) = x++z
    quicksort :: [Int] -> [Int]
    quicksort [] = []
    quicksort (x:xs) 
        | (l1 /= []    ) && (l2 /= []) = addi'(quicksort l1', quicksort l2')
        | l1 == [] = addi' (l1, quicksort l2)
        | l2 == [] = addi' (l1,l2)
            where
                (l1,l2) = splitBy' x (x:xs)
                (l1',l2') =  (addi'(splitBy' (x-1) l1),addi' (splitBy' (x+1) l2))

1 个答案:

答案 0 :(得分:9)

调试此类代码时,QuickCheck是一个非常有用的工具。

我将您的代码放入Test.hs,将其加载到ghci然后运行:

*Test> import Test.QuickCheck
*Test Test.QuickCheck> quickCheck $ \xs -> quicksort xs == Data.List.sort xs
*** Failed! Falsifiable (after 8 tests and 5 shrinks):    
[1,0]
*Test Test.QuickCheck> quicksort [1,0]
[1,0]

现在您有一个非常小的输入([1,0])来查看和跟踪您的代码:

  quicksort (1::0::[]) -- has (l1,l2) = splitBy' 1 [1,0] = ([1,0],[])
= addi' ([1,0], [])       -- because  `l2 == []`
= [1,0] ++ []
= [1,0]

据推测,您对splitBy'quicksort中的检查有不同的行为。检查此执行与您的意图的不同之处,您将找到如何修复代码。