C++ 二叉搜索算法像lower_bound一样工作

C++ Binary search algorithm to work like lower_bound

本文关键字:工作 一样 bound 搜索算法 lower C++      更新时间:2023-10-16

继我之前的 -

我正在创建一个带有二进制搜索的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;
    }

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);
}