我之前有另一个问题 -
我正在创建一个lower_bound
版本,其中包含二进制搜索。使用BinarySearch
函数,我找到了一个插入新项目的地方,并且对于循环,我会移动数组的其余部分并插入正确的项目,以便我可以将其插入到正确的位置。
但是以下BinarySearch
函数无法正常工作。
谁能明白为什么?
bool CReg::AddCar ( const char *name){
CArr * tmp = new CArr(name); // an item I am going to insert
int pos = BinarySearch(name,0,len); //len = number of items in array
checkLen(); // whether I do have enough space to move the array right
if (length!=0)
for (int i = 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 the new item should go to
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;
}
答案 0 :(得分:0)
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 the new item should go to
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;
}
但您可以直接使用std::lower_bound
:
// Assuming std::vector<std::string> Arr;
void CReg::AddCar(const std::string& name)
{
auto it = std::lower_bound(Arr.begin(), Arr.end(), name);
Arr.insert(it, name);
}