Index: ../trunk-jpl/src/c/shared/Sorting/binary_search.cpp =================================================================== --- ../trunk-jpl/src/c/shared/Sorting/binary_search.cpp (revision 13574) +++ ../trunk-jpl/src/c/shared/Sorting/binary_search.cpp (revision 13575) @@ -63,62 +63,49 @@ /*Return result: */ return found; } /*}}}*/ -int binary_search(int* poffset,double target,double* sorted_doubles,int num_doubles){ /*{{{*/ +int binary_search(int* poffset,double target,double* list,int num_doubles){ /*{{{*/ /*output: */ - int offset=0; - int found=0; /*found=0: not found. - found=1: found, and target is == to value at offset - found=2: found, and target is > to value at offset and < to value at offset+1 - */ + int offset = 0; + int found = 0; /*found = 0: not found. + found = -1: found, and target is < first element + found = 1: found, and target is == to value at offset + found = 2: found, and target is > to value at offset and < to value at offset+1 + found = 3: found, and target is >= last value */ /*intermediary: */ - double *beg = NULL; - double *end = NULL; - double *mid = NULL; + int n0 = 0; + int n1 = int(num_doubles/2); + int n2 = num_doubles-1; - // point to beginning and end of the array - beg = sorted_doubles; - end = sorted_doubles+num_doubles; - mid = beg+(int)(num_doubles/2.0); - - if (target<*beg){ + if(target=list[n2]){ + found = 3; + offset = n2-1; } - else if(*(end-1)==target){ - found = 1; - offset = num_doubles-1; - } else{ - while((beg <= end) && !( target>=*mid && target<*(mid+1)) ){ - // is the target in lower or upper half? - if (target < *mid) { - end = mid - 1; //new end - mid = beg + (end-beg)/2; //new middle + while(!found){ + /*did we find the target?*/ + if(list[n1]<=target && list[n1+1]>target){ + found = 1; + offset = n1; + break; } - else { - beg = mid + 1; //new beginning - mid = beg + (end-beg)/2; //new middle + if(target < list[n1]){ + n2 = n1; + n1 = n0 + int((n2-n0)/2); } + else{ + n0 = n1; + n1 = n0 + int((n2-n0)/2); + } } - - //did we find the target? - if( target>*mid && target<*(mid+1)){ - found=2; - offset=mid-sorted_doubles; - } - else if( target==*mid){ - found=1; - offset=mid-sorted_doubles; - } - else { - found=0; - } + + //did we find an exact target? + if(list[n1]==target) found = 2; } /*Assign output pointers:*/