C++ Binary search algorithm to work like lower_bound -
i have question following previous -
i creating version of lower_bound
binary search. binarysearch
function find place insert new item , cycle move rest of array , insert right item can insert right position.
but following binarysearch
function not work properly.
can see why?
bool creg::addcar ( const char *name){ carr * tmp = new carr(name); // item going insert int pos = binarysearch(name,0,len); //len = number of items in array checklen(); // whether have enough space move array right if (length!=0) (int = m_len; i>=pos; i-- ) arr[i+1] = spzarr[i]; arr[pos] = tmp; length++; checklen(); return true; } int binarysearch(const char * name, int firstindex, int lastindex) { if (lenght == 0) return 0; //number of items in array if (firstindex == lastindex) return lastindex; int tmp = lastindex - firstindex; int pos = firstindex + tmp / 2; //position new item should go if (tmp % 2)++pos; if (lastindex == pos || firstindex == pos) return pos; if (strcmp(name, arr[pos]) < 0) return binarysearch(name, firstindex, pos - 1); if (strcmp(name, arr[pos]) > 0) return binarysearch(name, pos + 1, lastindex); return pos; }
a fixed version of binarysearch
int binarysearch(const char* name, int firstindex, int lastindex) { if (firstindex == lastindex) return lastindex; int dist = lastindex - firstindex; int mid = firstindex + dist / 2; //position new item should go if (strcmp(name, arr[mid]) < 0) return binarysearch(name, firstindex, mid); if (strcmp(name, arr[mid]) > 0) return binarysearch(name, mid + 1, lastindex); return mid; }
but may directly use std::lower_bound
:
// assuming std::vector<std::string> arr; void creg::addcar(const std::string& name) { auto = std::lower_bound(arr.begin(), arr.end(), name); arr.insert(it, name); }
Comments
Post a Comment