ruby - Stack level too deep in recursive method -


when run code:

def binarysearch(key, arr, min, max)   if max < min       return -1   else     midpoint = arr[(arr.length-1)/2]     if midpoint < key       binarysearch(key, arr, midpoint, max)     elsif midpoint > key       binarysearch(key,arr, min, midpoint)     else       return midpoint     end   end end  arr = [0,1,2,3,6,77,23,1133,44,144,232,112] arr.sort! binarysearch(144, arr, arr.min, arr.max) 

i stack level deep error:

tree.rb:15:in `binarysearch': stack level deep (systemstackerror) tree.rb:15:in `binarysearch' ... 

is there reason why cannot find return statement when right block reached? suggested define initialize default of nil, activate first run.

1) ruby not need return statement - recursive algorithm does. however, not problem

2) midpoint = arr[(arr.length-1)/2]

this value never changes - every time call binarysearch, same value midpoint... on , on , over... forever.... why getting stack overflow.

because no matter how deep stack go, midpoint either < or > key... no matter do.

you need different each time in order change.

note: when call binarysearch within binarysearch - changing min/max values, not way calculating midpoint... think that.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

gradle error "Cannot convert the provided notation to a File or URI" -