Yexiaomo
程序入口就是需要定义 main() 方法看代码应该是C语言的折半查找算法,虽然文件后缀名是 .cpp ,按照C语言方式写应该没啥问题将你的定义数组放在main()方法中在程序的最后添加如下代码int main()
{
int v[20] = {1,2,3,4,5,6,7,8,9,10};
int index = binsearch(5, v, 10); //我这里查找的是 5
printf("查找 5 在数组中的位置为: %d", index);
return 0;
}
Yexiaomo
binsearch(5,v,10)含义就是在 v数组中查找 5这个数查找索引结束是 10--------------分割线-------------完整代码这样写#include <stdio.h>
int binsearch(int x, int v[20], int n)
{
int low, hight, mid;
low = 0;
hight = n - 1;
while(low <= hight)
{
mid = (low+ hight)/2;
if (x<v[mid]){
hight = mid-1;
}else{
low = mid+1;
}
mid = (low+hight)/2;
}
if (x == v[mid])
{
return mid;
}else{
return -1;
}
}
int main()
{
int v[20] = {1,2,3,4,5,6,7,8,9,10};
int index = binsearch(5, v, 10);
printf("查找 5 在数组中的位置为: %d", index);
return 0;
}