【发布时间】:2021-09-18 21:38:09
【问题描述】:
如果我在 x 中输入第 4 个索引元素,它运行正确,如果我在数组中输入其他元素,它返回 -1
#include<stdio.h>
int Binary_search(int A[],int n,int x)
{
int start=0,end = n-1;
while(start<=end)
{
int mid = (start+end)/2;
if(x == A[mid])return mid;
else if(x < A[mid]) end = mid-1;
else start = mid+1;
}
return -1;
}
int main()
{
int A[] = {3,23,26,51,72,77,42,64};
puts("Enter the element ");
int x; scanf("%d",&x);
int len = sizeof(A)/sizeof(A[0]);
int index = Binary_search(A,len,x);
if(index != -1) printf("Number %i is at index %i",x,index);
else printf("It's not in the array");
}
【问题讨论】:
-
二分查找,需要对数组进行排序,这里不是这样。
标签: arrays c algorithm sorting binary-search