0

在我之前的问题之后,我还有另一个问题 -

我正在创建一个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;
    }
4

1 回答 1

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);
}
于 2015-04-15T11:25:44.253 回答