思路:
先把中间元素找到,寻找的元素在中间元素左边,则小于中间元素,改变right。再继续折半找中间元素寻找。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int Binary(int x, int arr[], int left, int right)
{
int mid = 0;
while (left <= right)
{
int mid = left - (left - right) / 2;
if (x > arr[mid])
{
left = mid + 1;
}
else if (x < arr[mid])
{
right = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[] = { 1, 3, 4, 6, 7, 8, 56, 67, 78 };
int size = sizeof(arr) / sizeof(arr[0]);
int ret = Binary(78, arr, 0, size - 1);
if (ret == -1)
{
printf("not exsit");
}
else
{
printf("%d", ret);
}
system("pause");
return 0;
}
转载于:https://blog.51cto.com/10740184/1704984