C++ Binary search like lower_bound -


i have problem binary search should work little lower_bound. gives me segfault in 5th run. can see problem ? thanks

int binarysearch ( const char * a, int firstindex , int lastindex){     if (m_len == 0) return 0; //number of items in searched array     if ( firstindex == lastindex ) return lastindex;     int tmp = lastindex - firstindex;     int pos = tmp/2;     if ( tmp % 2 != 0 ) ++pos;     if (strcmp(a,arr[pos]) < 0) return binarysearch(a,firstindex,pos-1);     if (strcmp(a,name) > 0) return binarysearch(a,pos+1,lastindex);     return pos; } 

int tmp = lastindex - firstindex;

should be:

int tmp = lastindex + firstindex; 

that because looking middle of indexes x , y (x+y)/2.

your code's behaviour should unpredictable, possibly looping , causing segmentation fault.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -