二分法只是用于有序的数组,如果是无序输入,还需要进行排序。此外,mid 中间值不是整数,要取整。
#include <stdio.h>
#include <stdlib.h>
int Bin_search(int* p, int len, int target)
{
int left = 0;
int right = len - 1;
while (left < right)
{
int mid = (left + right) / 2;
if (p[mid] == target)
{
return mid;
}
else if (p[mid] < target)
{
left = mid + 1;
}
else if (p[mid] > target)
{
right = mid - 1;
}
}
return left;
}
int main()
{
int len;
int target;
scanf_s("%d", &len);
scanf_s("%d", &target);
int i;
int* p = (int*)malloc(sizeof(int) * len);
if (p == NULL)
{
return 0;
}
else
{
for (i = 0; i < len; i++)
{
scanf_s("%d", &p[i]);
}
}
int result = Bin_search(p, len, target);
printf("%d", result);
free(p);
return 0;
}
结果
数组长度为4,目标值为5,数组元素为1 3 5 6 ,目标值得位置(索引)为2