c++ - 二进制搜索插入字符字符串。错误在哪里?

标签 c++ algorithm sorting binary-search

我有一个字符串数组。我必须通过二进制搜索算法在字符串数组中找到一个 char 字符串。如果有这个字符串,那么函数必须返回位置并返回 true,否则该函数必须返回位置以在数组中插入字符串和 false。 我有一个错误,但我不知道在哪里 ((

例子:

bool Binary_search ( char * arr_strings[], int & position, const char * search_string )
{
    int start = 0 ;
    int end = 10 - 1; // arr_strings [10]
    int for_compare;
    int middle;

    while ( start <= end )
    {
        middle = ( start + end ) / 2;
        for_compare = strcmp ( arr_strings[middle], search_string  );

        if ( for_compare > 0 )
        {
            start = middle + 1;
        } 
        else if ( for_compare < 0 )
        {
            end = middle - 1;
        }
        else
        {
            // if search_string is found in array, then function return position in array of strings and return true
            position = middle;
            return true;
        }
    }
    // if search_string is not found in array, then function must return position for insert string and return false 
    position = middle;
    return false;
}

最佳答案

我想也许应该是:

if ( for_compare > 0 )
{
    end = middle - 1;
} 
else if ( for_compare < 0 )
{
    start = middle + 1;
}

关于c++ - 二进制搜索插入字符字符串。错误在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15891661/

相关文章:

c++ - MSXML2::IXMLDOMDocument2* 的静态实例变得无效

php - 对 PHP 数组进行排序

C++ 倒置加权随机播放

Javascript 排序函数错误地更改元素在数组中的位置

sorting - 多个 solr 服务器实例上的 solr.RandomSortField

c++ - C++类成员的条件布局

C++ std::list with struct containing list with struct

c++ - 从 ant 运行 ndk-build

algorithm - 生成给定长度的 0's and 1' 的所有组合,最小和最大为 1

algorithm - shell脚本中关联数组的时间复杂度