【代码】
#include "array.h"
#define N 10
int binSearch(int a[], int n,int key,int left,int right)
{
int mid;
if (left > right) return -1;//出口1
else
{
mid = (left + right) / 2;
if (a[mid] == key) return mid;//出口2
else
if (key < a[mid])
{
right = mid - 1;
binSearch(a, n, key, left, right);//改变传入实参后的自调用
}
else
{
left = mid + 1;
binSearch(a, n, key, left, right);//改变传入实参后的自调用
}
}
}
int main()
{
int a[N], x, pos,left=0,right=N-1;
init(a, N);//构造测试数据
uparray(a, N);//排序
print(a, N);
printf("请输入待查询数据:");
scanf_s("%d", &x);
pos = binSearch(a, N, x,left,right);//二分查找
if (pos != -1)
printf("a[%d]=%d\n", pos, x);
else printf("查找失败!\n");
return 0;
}