二分查找

第一步

#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; }

二分查找_第1张图片


你可能感兴趣的:(二分查找)