Ruby Stack Level Too Deep Error

时间:2018-06-16 20:38:54

标签: ruby algorithm sorting quicksort

我正在将Python中的一些代码改编为Ruby,它定义了#partition方法和#quicksort方法。由于#partition方法中的可枚举,我遇到了“Stack Level Too Deep”错误:

(low..high).map do |j| 

#partition方法可以自行查找,所以我不确定我是否拥有正确的可枚举,并且非常感谢任何建议。 (另外,我知道Ruby有一个#partition方法;这只是为了好奇心。)谢谢!

# This function takes last element as pivot, places
# the pivot element at its correct position in sorted
# array, and places all smaller (smaller than pivot)
# to left of pivot and all greater elements to right
# of pivot

def partition(arr, low, high)
  i = low - 1   #index of smaller element
  pivot = arr[high]   #pivot

  (low..high).map do |j|
    #if current element is smaller than or equal to pivot
    if arr[j] <= pivot
      #increment index of smaller element
      i = i + 1
      arr[i], arr[j] = arr[j], arr[i]
    end
  end
  arr[i+1], arr[high] = arr[high], arr[i+1]
  return i+1
end

def quicksort(arr, low, high)
  if low < high
    pi = partition(arr, low, high)
    quicksort(arr, low, pi-1)
    quicksort(arr, pi+1, high)
  end
end

1 个答案:

答案 0 :(得分:2)

尝试(low...high).each do |j|

even betterarr = [10, 7, 8, 9, 1, 5] n = arr.size quicksort(arr, 0, n-1) p arr # => [1, 5, 7, 8, 9, 10] steenslag指出。

这是因为Python在一步之前打破了循环。

(0..10).each {|n| p n}

Ruby中的这个循环打破10

for j in range(0 , 10):
    print (j)

Python中的这个循环在9处打破:

{{1}}