1 // To Compile and Run: g++ binary_search.cc -std=c++11 -Wall -O3 && ./a.out 8 2 3 4 #include <stdlib.h> 5 #include <assert.h> 6 7 #include <iostream> 8 #include <vector> 9 10 11 int BinarySearch(const std::vector<int> &inArr, int target) { 12 int left = 0; 13 int right = inArr.size() - 1; 14 15 while (true) { 16 if (left > right) { 17 std::cout << "Failed to find: " << target << " "; 18 return -1; 19 } 20 21 int mid = left + (right - left) / 2; 22 if (target == inArr[mid]) { 23 return mid; 24 } 25 26 if (target > inArr[mid]) { 27 right = mid - 1; 28 } 29 // target < inArr[mid] 30 else { 31 left = mid + 1; 32 } 33 } 34 35 std::cerr << "Could never reach here. "; 36 return -1; 37 } 38 39 int main(int argc, char const *argv[]) { 40 const std::vector<int> arr { 41 8, 7, 4, 3, -5, -9 42 }; 43 assert(argc >= 2); 44 int target = atoi(argv[1]); 45 46 int indexOfTarget = BinarySearch(arr, target); 47 if (indexOfTarget < 0) { 48 std::cout << "Failed to find: " << target << " "; 49 return -1; 50 } 51 std::cout << "Find: " << target << " in " << indexOfTarget << " "; 52 53 return 0; 54 }
对于顺序排列的数组,只修改26行的符号就行了。
使用递归实现,只需要在BinarySearch函数中去掉while循环,判断结束后,return自身就行了。
代码如下:
1 // To Compile and Run: g++ binary_search.cc -std=c++11 -Wall -O3 && ./a.out 8 2 3 4 #include <stdlib.h> 5 #include <assert.h> 6 7 #include <iostream> 8 #include <vector> 9 10 11 int BinarySearchRecursive(const std::vector<int> &inArr, int target, int left, int right) { 12 if (left > right) { 13 std::cout << "Failed to find: " << target << " "; 14 return -1; 15 } 16 17 int mid = left + (right - left) / 2; 18 if (target == inArr[mid]) { 19 return mid; 20 } 21 22 if (target > inArr[mid]) { 23 right = mid - 1; 24 } 25 else { 26 left = mid + 1; 27 } 28 29 return BinarySearchRecursive(inArr, target, left, right); 30 } 31 32 int main(int argc, char const *argv[]) { 33 const std::vector<int> arr { 34 8, 7, 4, 3, -5, -9 35 }; 36 assert(argc >= 2); 37 int target = atoi(argv[1]); 38 39 int indexOfTarget = BinarySearchRecursive(arr, target, 0, arr.size() - 1); 40 if (indexOfTarget < 0) { 41 std::cout << "Failed to find: " << target << " "; 42 return -1; 43 } 44 std::cout << "Find: " << target << " in " << indexOfTarget << " "; 45 46 return 0; 47 }