gpt4 book ai didi

optimization - 在 Haskell 中优化基数排序

转载 作者:行者123 更新时间:2023-12-03 15:52:27 25 4
gpt4 key购买 nike

我还在学习 Haskell,我写了以下基数排序函数。它似乎工作正常,但问题是它的内存效率相当低。如果使用 ghc 编译,内存已经超过 500MB,输入列表大小为 10000 个元素。

所以我想问你如何改进以下算法/代码以使其在速度和内存方面更有效。最好的起点是什么?

import System.Random

-- radixsort for positive integers. uses 10 buckets
radixsort :: [Int] -> [Int]
radixsort [] = []
radixsort xs =
-- given the data, get the number of passes that are required for sorting
-- the largest integer
let maxPos = floor ((log (fromIntegral (foldl max 0 xs)) / log 10) + 1)

-- start sorting from digit on position 0 (lowest position) to position 'maxPos'
radixsort' ys pos
| pos < 0 = ys
| otherwise = let sortedYs = radixsort' ys (pos - 1)
newBuckets = radixsort'' sortedYs [[] | i <- [1..10]] pos
in [element | bucket <- newBuckets, element <- bucket]

-- given empty buckets, digit position and list, sort the values into
-- buckets
radixsort'' [] buckets _ = buckets
radixsort'' (y:ys) buckets pos =
let digit = div (mod y (10 ^ (pos + 1))) (10 ^ pos)
(bucketsBegin, bucketsEnd) = splitAt digit buckets
bucket = head bucketsEnd
newBucket = bucket ++ [y]
in radixsort'' ys (bucketsBegin ++ [newBucket] ++ (tail bucketsEnd)) pos
in radixsort' xs maxPos

-- get an random array given an seed
getRandIntArray :: Int -> [Int]
getRandIntArray seed = (randomRs (0, div (maxBound :: Int) 2) (mkStdGen seed))

main = do
value <- (\x -> return x ) (length (radixsort (take 10000 (getRandIntArray 0))))
print value

最佳答案

主要问题是您的功能 radixsort'' , 因为 ++是 O(n) 并且它每次都复制作为第一个参数给出的列表。

pack (-1) r' _ = r'
pack n r' relems =
let getn = (map snd) . (filter ((n==) . fst))
in pack (n - 1) ((getn relems):r') relems
radixsort'' elems pos =
let digit = \y -> div (mod y (10 ^ (pos + 1))) (10 ^ pos)
relems = zip (map digit elems) elems
in pack 9 [] relems

关于optimization - 在 Haskell 中优化基数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5277552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com