美文网首页
2018-10-06

2018-10-06

作者: yangxiaosu | 来源:发表于2018-10-06 23:43 被阅读0次

    #include <iostream>

    using namespace std;

    int main()

    {int binary_search(int*a,int n,int x);

    int n=10;

    int p=6;

    int q;

    int sorted_array[n]={1,2,3,4,5,6,7,8,9,10};

    q=binary_search(sorted_array,n,p);

    if (q==-1)

        cout<<"Not Found"<<endl;

    else

        cout<<"idx="<<q+1<<endl;

    return 0;

    }

    int binary_search(int*a,int n,int x)

    {int low=0;

    int high=n-1;

    int mid;

    while(low<=high)

    {

      if(a[low]==x)

        return (low);

      if(a[high]==x)

        return (high);

      mid=low+(high-low)/2;

      if(a[mid]==x)

        return (mid);

      if(a[mid]<x)

        low=mid+1;

      else

        high=mid-1;

    }

    if(low>high)

            return (-1);

    }

    相关文章

      网友评论

          本文标题:2018-10-06

          本文链接:https://www.haomeiwen.com/subject/jvekaftx.html