/* 二分查找示例示例 -- 只适合已排序数组 Wirtten by: nick Date: 2012-10-16 12:13 */ #include <iostream> #include <iomanip> using namespace std; bool binarySearch(int list[], int end, int target, int& index); int main() { int a[10] = {0,1,2,3,4,5,6,7,8,9}; //已排序数组 int ans=0; if(binarySearch(a, 9, 6, ans)) cout << "Find! index = " << ans; return 0; } bool binarySearch(int list[], int end, int target, int& index) { int first = 0; int last = end; int mid; while(first<=last) { mid = (first + last) / 2; if(target < list[mid]) last = mid - 1; else if(target > list[mid]) first = mid + 1; else { index = mid; break; } } return (list[mid] == target); }