#include \n#include \n\nusing namespace std;\n\n// 二分算法模板函数\nint binarySearch(vector& nums, int target) {\n int left = 0;\n int right = nums.size() - 1;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n \n if (nums[mid] == target) {\n return mid;\n } else if (nums[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n } \n }\n \n return -1;\n}\n\nint main() {\n // 在这里进行测试\n vector nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n int target = 6;\n \n int result = binarySearch(nums, target);\n \n if (result != -1) {\n cout << "目标元素 " << target << " 的索引是 " << result << endl;\n } else {\n cout << "目标元素 " << target << " 不存在" << endl;\n }\n \n return 0;\n}\n\n这个模板函数接受一个已排序的整数向量 nums 和一个目标整数 target,并返回目标整数在向量中的索引。如果目标整数不存在于向量中,则返回 -1。函数通过不断更新左右边界的方式进行二分查找。在主函数中,我们使用一个已排序的向量和一个目标整数进行测试,并输出结果。\n\n希望这个模板函数能够帮助你理解二分算法的分治思想!


原文地址: https://www.cveoy.top/t/topic/pMCh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录