Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

algorithm - Stack Level Too Deep for Merge Sort in Ruby

I'm practicing Merge Sort in Ruby and am running into an error where my Stack Level is too Deep. Here is the code:

def sort(numbers)

    num_length = numbers.length
    if num_length <= 1
        numbers
    end

    half_of_elements = (num_length / 2).round

    left = numbers.take(half_of_elements)
    right = numbers.drop(half_of_elements)

    sorted_left = sort(left)
    sorted_right = sort(right)

    print sorted_left, sorted_right
    #merge(sorted_left, sorted_right)
end

I've commented out the merge method because I just want to see the sorted arrays, but my code keeps getting stuck and I get the error. Can anyone help me figure out what's wrong?

question from:https://stackoverflow.com/questions/65850105/stack-level-too-deep-for-merge-sort-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You failed to return numbers in your guard condition. So it just skips past that and calls itself recursively with the same argument.

When you get a stack level too deep on a recursive call that usually means you have a recursive case that winds up making the same call. I debug those by adding a print at the start of the recursive call. Once I see the call that is leading to calling itself, I walk through what happens for that case very carefully.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...