#include <iostream> #include <algorithm> using namespace std; int binary_search(int * num, int begin, int end, int target) //对num[begin, end] 进行二分查找。 找到返回位置, 否则返回-1 { int i = begin; int j = end; int middle; while (i <= j) { middle = i + (j - i) / 2; if (num[middle] > target) { j = middle - 1; } else if (num[middle] < target) { i = middle + 1; } else { return middle; } } return -1; } int num[10] = {1,3,5,6,8,9,10,13,15,19}; int main() { printf("%d/n", binary_search(num, 0, 9, 1) ); printf("%d/n", binary_search(num, 0, 9, 2) ); printf("%d/n", binary_search(num, 0, 9, 3) ); printf("%d/n", binary_search(num, 0, 9, 4) ); printf("%d/n", binary_search(num, 0, 9, 5) ); printf("%d/n", binary_search(num, 0, 9, 6) ); printf("%d/n", binary_search(num, 0, 9, 7) ); printf("%d/n", binary_search(num, 0, 9, 8) ); printf("%d/n", binary_search(num, 0, 9, 9) ); printf("%d/n", binary_search(num, 0, 9, 10) ); printf("%d/n", binary_search(num, 0, 9, 11) ); printf("%d/n", binary_search(num, 0, 9, 12) ); printf("%d/n", binary_search(num, 0, 9, 13) ); printf("%d/n", binary_search(num, 0, 9, 14) ); printf("%d/n", binary_search(num, 0, 9, 15) ); printf("%d/n", binary_search(num, 0, 9, 16) ); printf("%d/n", binary_search(num, 0, 9, 17) ); printf("%d/n", binary_search(num, 0, 9, 18) ); printf("%d/n", binary_search(num, 0, 9, 19) ); printf("%d/n", binary_search(num, 0, 9, 20) ); printf("%d/n", binary_search(num, 5, 9, 17) ); }
据说:
http://news.csdn.net/a/20100423/218099.html