在我之前的问题之后,我还有另一个问题 -
我正在创建一个lower_bound
带有二进制搜索之类的版本。随着BinarySearch
功能,我找到了插入新项目的位置,并且使用 for 循环,我确实移动了数组的其余部分并插入了正确的项目,以便我可以将其插入到正确的位置。
但是下面的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;
}