用C进行二进制搜索

时间:2015-09-08 20:04:34

标签: c algorithm search runtime-error binary-search

我完全理解这个概念哦二进制搜索是如何工作的以及需要发生什么,但是当试图用C实现时,搜索还没有成功过。我真的可以使用一个很好的解释我的错误存在的位置,为什么它容易出错以及重写它的正确方法。这不是我想指出的家庭作业,而只是一个必须通过我才能通过计算机科学II的主题。这是代码。

#include<stdio.h>

int main(int argc, char** argv) {       
    int array[11] = {11,24,47, 57,58,59,89,94,102,150,250};

    int n = sizeof(array)/4;             
    int key;                         

    int topIndex = n-1;        
    int bottomIndex = 0;        

    int middleIndex = (topIndex + bottomIndex) / 2; 

    printf("%d is the initial middle index position which contains the integer %d\n\n", middleIndex, array[middleIndex]);

    scanf("%d", &key);
    printf("%d was read in, i will now search for the number\n\n", key);

    while(bottomIndex<=topIndex)
    {
        if(key==array[middleIndex])
        {
          printf("I found %d in %d\n\n", key, middleIndex);
          break;
        }
        else if(key<array[middleIndex])
        {
            topIndex = middleIndex-1;
            middleIndex = (topIndex + bottomIndex) / 2;
            printf("Middle Index: %d , Top Index: %d , Bottom Index: %d\n\n", middleIndex, topIndex, bottomIndex);

        }

    }


    return 0;
}

1 个答案:

答案 0 :(得分:1)

当密钥超过bottomIndex的值时,您不会移动middleIndex

是一个固定版本
while (bottomIndex <= topIndex)
{
  if (key == array[middleIndex])
  {
    printf("I found %d in %d\n\n", key, middleIndex);
    break;
  }
  else if (key<array[middleIndex])
    topIndex = middleIndex - 1;
  else
    bottomIndex = middleIndex + 1; // This part was lacking

  // This code is common to both cases above
  middleIndex = (topIndex + bottomIndex) / 2;
  printf("Middle Index: %d , Top Index: %d , Bottom Index: %d\n\n", middleIndex, topIndex, bottomIndex);
}