gpt4 book ai didi

ruby - 快速排序实现 : stack level too deep (SystemStackError)

转载 作者:数据小太阳 更新时间:2023-10-29 07:48:42 26 4
gpt4 key购买 nike

所以我试图在 ruby​​ 中实现快速排序,但我得到了这个错误 `quicksort': stack level too deep (SystemStackError)

def quicksort(array)
if array.length <= 1
return array
end
less = Array.new
greater = Array.new
pivot = array[array.length/2]
array.each do |x|
if x < pivot
less << x
else
greater << x
end
end
return quicksort(less) << pivot << quicksort(greater)
end

编辑我将 else 更改为 elsif x > pivot 并且它似乎有效。

最佳答案

你的算法对我有用,当我生成一个数组进行测试时甚至达到 1e7。

 quicksort Range.new(1,1e7).to_a.shuffle

当然,这需要大约 4.5 GB 的 RAM 才能完成。至于清理输出......

ruby-1.9.3-p0 :018 >       quicksort [1,3,2] # => [1, 2, [], 3, []] 
ruby-1.9.3-p0 :019 > quicksort [1,4,2,3] # => [1, 2, [3, [4]]]

改变这一行:

  return (quicksort(less) << pivot << quicksort(greater)).flatten.compact

它使一切变得更干净。

ruby-1.9.3-p0 :037 >       quicksort [1,3,2] # => [1, 2, 3] 
ruby-1.9.3-p0 :038 > quicksort [1,4,2,3] # => [1, 2, 3, 4]

关于ruby - 快速排序实现 : stack level too deep (SystemStackError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8057786/

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