def quick_sort(list)
return list if list.size <= 1
p = list.sample
left, right = list.partition{|elmt| elmt <= p}
quick_sort(left) + quick_sort(right)
end
a = [9,8,7,6,5,0,6]
b = quick_sort(a)
puts b
我真没看出有何问题。但是却报错:4: stack level too deep (SystemStackError)
第四行left, right = list.partition{|elmt| elmt <= p}
有何问题?
多谢!
def q_sort(array)
return array if array.length < 2
pivot = array.pop
less, more = array.partition { |i| i < pivot }
q_sort(less) + [pivot] + q_sort(more)
end
1.9.3p448 :001 > a = [1,2,3,4,5,6]
=> [1, 2, 3, 4, 5, 6]
1.9.3p448 :002 > a.sample
=> 4
1.9.3p448 :003 > a.sample
=> 2
1.9.3p448 :004 > a.sample
=> 4
1.9.3p448 :005 > a.sample
=> 4
1.9.3p448 :006 > a.sample
=> 3
1.9.3p448 :007 > a.sample
=> 3
1.9.3p448 :008 >
不知道你的根据是什么?
直接在p = list.sample
下面加的 puts p
def quick_sort(list)
return list if list.size <= 1
p = list.sample
puts p
left, right = list.partition{|elmt| elmt <= p}
quick_sort(left) + quick_sort(right)
end
ruby 2.0.0p247