二进制搜索中出现无限循环,为什么?

时间:2014-05-03 12:39:54

标签: c string binary-search

我收到了一个使用C中的指针和内存分配来编写字典的作业。 一切正常,但我实现的二进制搜索行为很奇怪(我无法找到导致该行为的特定模式): 有时用户在compare中输入一个字符串并将其复制到search后(分配后)它只搜索但没有找到但永远不会离开循环,这里是代码: 搜索使用的数组是排序的,并且没有任何重复值,数组的每个元素都保存一个字符串的地址,我将不胜感激任何帮助。

void bin_search (char **word, char **definitions_1 ,char **definitions_2, int limit)
{
   int first, //start value for binary search
   last, //last value for binary search
   middle;  //middle value for binary search
   char compare [81], //will get the word to search
    *search, //will hold the string after memory allocation
    ESC [5] = "Exit"; //this string holds exit value for comparison
 do
  {
        first = 0;
    last = limit-1;
    middle = limit/2;
    compare [81];
    free(search); //memory allocated to search pointer is freed (allocation will take place upon next search)
    printf("Please enter a word (exit to terminate):\n");
    scanf("%s", compare); //gets desired word to search for
    search = (char*) malloc (strlen (compare)+1);
    if (search == NULL)
    {
        printf ("Memory allocation failed!\n");
        exit (1);
    }
    strlwr (compare+1); //each of the letters (excluding the first one) will be chaneged to lower case letters
    if ((int) *(compare) >= ASCII_a) //if the first [element] letter of a string [word] is a lower case letter
    {
        *compare = (char)(((int) *(compare)) - ASCII_CAPIAL_DIF); //the lower case letter will be changed to upper case one by subtracting the constat difference of 32
    }
    strcpy (search, compare);
        while (first <= last && strcmp (search, ESC) != 0)
    {
        printf("\nsearching\n");
        if (strcmp (word [middle], search) < 0)
        {
            first = middle+1;
        }
        else if (strcmp (word [middle], search) == 0)
        {
            if (definitions_2 [middle] == NULL) //if the word has only one definition, the second NULL one won't be diaplayed
            {
                printf("The word '%s' #%d has 1 definition:\n\n1.%s\n\n", search, middle, definitions_1 [middle]);

            }
            else //if the word has two defenitons - two of them will be disaplayed
            {
                printf("%s\n", definitions_2 [middle]);
                printf("The word '%s' #%d has 2 definitions:\n\n1.%s\n\n2.%s\n\n", search, middle, definitions_1 [middle], definitions_2 [middle]);
            }
            break;
        }
        else
        {
            last = middle-1;
            middle = ((first+last)/2);
        }
    }
    if (first > last && strcmp (compare, ESC) != 0)
    {
        printf("'%s' is an unknown word!\n", search);
    }
} while (strcmp (compare, ESC) != 0);
}

1 个答案:

答案 0 :(得分:1)

有时在没有所有细节的情况下查看代码结构会很有帮助

    if (strcmp (word [middle], search) < 0)
    {
        first = middle+1;
    }
    else if (strcmp (word [middle], search) == 0)
    {
        break;
    }
    else
    {
        last = middle-1;
        middle = ((first+last)/2);
    }