#include <iostream> using namespace std; #include <assert.h> //方法1:区间为[ ] /* int BinarySearch(int* a, int size, int x) { assert(a); int left = 0; int right = size - 1; while (left <= right) { int mid = left+(right - left) / 2; if (a[mid] < x) { left = mid + 1; } else if (a[mid] > x) { right = mid - 1; } else { return mid; } } return -1; }*/ //方法2:区间为[ ) int BinarySearch(int* a, int size, int x) { assert(a); int left = 0; int right = size; while (left < right) { int mid = left + (right - left) / 2; if (a[mid] < x) { left = mid + 1; } else if (a[mid] > x) { right = mid; } else { return mid; } } return -1; } void Test() { int array[] = {0, 1, 2, 3, 4, 5, 6, 7}; cout<<BinarySearch(array, sizeof(array)/sizeof(array[0]), 0)<<endl; } int main() { Test(); return 0; }
时间: 2024-10-16 14:43:15