• 二分查找


    #include<iostream>
    using namespace std;

    int BinarySearch(int a[],int n,int goal)
    {
     for(int i=0;i<=n;i++)
     cout<<a[i]<<endl;
     int mid,low=0,high=n;
     while(low<=high)
     {
      mid=(low+high)/2;
      if(goal==a[mid])
       return mid;
      else if(goal<a[mid])
       high=mid-1;
      else
       low=mid+1;
     }
     return -1;
    }
    int main()
    {
     int arr[10]={0,3,7,9,11,35,66,78,89,100};
     int a;
     while(cin>>a)
     {
      int b;
      b=BinarySearch(arr,9,a);
      cout<<b<<endl;
     }
     return 0; 
    }

    //非递归算法

    int BinarySearch()

    {

          int low=0,high=n-1;

          int temp;

          while(low<=high)

          {

               temp=(low+high)/2;

               if(k==R[temp])

               {

                     return temp;

               }

               else if(k<R[temp])

               {

                     high=temp-1;

               }

               else

               {

                     low=temp+1;

               }

          }

          return -1;

    }

  • 相关阅读:
    mapreduce 函数入门 三
    *hiho 1475
    hiho 1571
    hiho 1620
    hiho 1613
    centos下nginx配置
    hiho 1617
    hiho 172周
    uva 11584
    hiho1605
  • 原文地址:https://www.cnblogs.com/qingcheng/p/2026313.html
Copyright © 2020-2023  润新知