标签:二分查找
#include<iostream> #include<assert.h> using namespace std; int BinarySearch(int*a, int size, int x) { assert(a); int left = 0; int right = size - 1;//闭区间[] //int right=size;//开区间[) while (left <= right) //while(left<right) { int mid = left + ((right - left) >> 1); if (a[mid] < x) { left = mid + 1; } else if (a[mid]>x) { right = mid - 1; //right=mid; } else { return mid; } } return -1; } int main() { int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int ret = BinarySearch(a, 10, 5); cout << ret << endl; system("pause"); return 0; }
标签:二分查找
原文地址:http://frankenstein.blog.51cto.com/10918184/1787550