欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找

程序员文章站 2022-06-06 13:38:27
...

第一步

#include<iostream>
using namespace std;

int binarySearch(int a[], int x, int n)
{
    int left=0;
    int right=n-1;
    while(left <= right)
    {
         int middle=(left + right) / 2;
         if(x == a[middle])
              return middle;
         else if(x > a[middle])
              left = middle+1;
         else if(x < a[middle])
              right = middle -1;
    }
    return -1;
}

int main()
{
    int a[10] = {1, 3, 4, 56, 78, 98,743,2423,5324,45336};
    int x;
    while(cin>>x)
    {
        cout<<binarySearch(a, x, 10)<<endl;
    }
    return 0;
}

二分查找