int BinarySearch(int key)
{
int left; //left var
int right; //right var
int middle;
left = 0;
right = MAX-1; //MAX is the number of array members
while(left <= right)
{
middle = (left+right)/2;
if(key < Data[middle])
right = middle -1;
else if (key > Data[middle])
left = middle+1;
else if (key == Data[middle])
printf("Find it! Data[%d] \n",middle)
return 1; //1 means succes
}
}
{
int left; //left var
int right; //right var
int middle;
left = 0;
right = MAX-1; //MAX is the number of array members
while(left <= right)
{
middle = (left+right)/2;
if(key < Data[middle])
right = middle -1;
else if (key > Data[middle])
left = middle+1;
else if (key == Data[middle])
printf("Find it! Data[%d] \n",middle)
return 1; //1 means succes
}
}
博客展示了一段用C语言实现二分查找算法的代码。代码中定义了二分查找函数,通过不断更新左右边界,在数组中查找指定的键值,若找到则输出位置并返回成功标识。
1437

被折叠的 条评论
为什么被折叠?



