简体   繁体   English

C ++二进制搜索算法像Lower_bound一样工作

[英]C++ Binary search algorithm to work like lower_bound

I do have another question following my previous - 我之前有另一个问题-

I am creating a version of lower_bound with something like binary search. 我正在使用类似二进制搜索的方法创建一个lower_bound版本。 With the BinarySearch function I find a place where to insert the new item and with the for cycle I do move the rest of the array and insert the right item so I can insert it to the right position. 使用BinarySearch函数,我找到了一个插入新项目的地方,使用for循环,我确实移动了数组的其余部分并插入了正确的项目,以便可以将其插入到正确的位置。

But the following BinarySearch function does not work properly. 但是以下BinarySearch函数无法正常工作。

Can anyone see why? 谁能看到原因?

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

A fixed version of BinarySearch 固定版本的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;
}

But you may directly use std::lower_bound : 但是您可以直接使用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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM