二进制搜索插入字符串。这个bug在哪里?

时间:2013-04-09 01:10:06

标签: 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;
}

2 个答案:

答案 0 :(得分:1)

问题是您的插入位置不正确。

您应该执行以下操作:

bool Binary_search ( char * arr_strings[], const char * search_string )
{           //^^^you are not doing recursive, so you don't need position as parameter 
    int start = 0 ;
    int end = 10 - 1; // arr_strings [10]
    int for_compare;
    int middle;
    int position = -1; 

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

        if ( for_compare > 0 )
        {   //^^^here should switch the order
            end = middle - 1;
        } 
        else if ( for_compare < 0 )
        {
            start = middle + 1;
        }
        else
        {
            position = middle;
            return true;
        }
    }

    if (position == -1)
    {
        if(strcmp(arr_strings[middle],search_string) <0 )
        {
            position = middle + 1;
        }else 
        {
            position = middle;
         }
    }

    return position;
}

答案 1 :(得分:1)

我想也许应该是:

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