无法通过所有测试用例

时间:2017-02-24 20:44:07

标签: c pointers binary-search

问题: 编写C程序以实现二进制搜索算法。

包含一项功能 int BinarySearch(int,int,int *,int x)---第一个参数是列表或数组的下限,第二个参数是列表或数组的上限,第三个参数是指向列表或数组的指针array和第四个参数是search元素。

请注意,该功能会返回搜索元素的索引。如果数组中不存在搜索元素,则返回-1。 假设数组的最大大小为10。请注意,如果a是数组,则[0]位于0位置,[1]位于位置1 ...

我尝试了这个,但它的测试用例传递仅占75%,如果n = 1则无法找到该元素;提前感谢:)

#include<stdio.h>
int BinarySearch(int, int ,int *, int);
int main(){
  int first=0, last; 
  int a[20],search,s=0,n,i;
  //int j,temp=0;
  printf("Enter the number of elements :\n");
  scanf("%d",&n);
  printf("Enter the elements :\n");
  for(i=0;i<n;i++)
  {
    scanf("%d",&a[i]);
  }
  printf("Enter the element to be searched :\n");
  scanf("%d",&search);
  last=n-1;

  s=BinarySearch(first, last, a, search);
  if(s>0){
  printf("The element %d is in position %d",search,s);
  }
  else{
  printf("The element %d is not present in the array",search);
  }
  return 0;
}

int BinarySearch(int l, int h, int *a, int x)
{
  int mid;
  while(l<=h){
    mid=(l+h)/2;
    if (x==a[mid])
      return mid;
  else if(x<a[mid])
    h=mid-1;
  else if(x>a[mid])
    l=mid+1;
    }
return -1;
}

0 个答案:

没有答案
相关问题