源代码:
#include <iostream> #include <string> using namespace std; typedef struct _Table { int data[100]; int length; }Table; int BinarySearch(Table a, int k) { int left = 0; int right = a.length - 1; while (left <= right) { int mid = (left + right) / 2; if (k < a.data[mid]) { right = mid - 1; } else if (k > a.data[mid]) { left = mid + 1; } else { return mid; } } return -1; } int main() { Table b = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, 12 }; cout << BinarySearch(b, 2) << endl; system("pause"); return 0; }
原文:http://www.cnblogs.com/yongssu/p/4395642.html