简单二分(折半查找)

二分算法复杂度:O(log2n)

 1 int BinarySearch(const int test[], int len, int target)
 2 {
 3     int left = 0, right = len - 1, mid;
 4     while (left <= right)
 5     {
 6         mid = (left + right) / 2;
 7         if (test[mid] == target)
 8         {
 9             return mid;
10         }
11         else if (test[mid] > target)
12         {
13             right = mid-1;
14         }
15         else
16         {
17             left = mid+1;
18         }
19     }
20     return -1;
21 }

测试用例:

 1 int main()
 2 {
 3     int test[10] = {1, 2, 4, 3, 5, 6, 9, 66, 33, 8};
 4     int len = sizeof(test) / sizeof(test[0]);
 5     sort(test, test + len);//(头文件:algorithm)
 6     for (auto i : test)
 7     {
 8         cout << i << "  ";
 9     }
10     cout << endl;
11     cout << "查询结果:" << BinarySearch(test, len, 66);
12 
13     return 0;
14 }