不想废话了!
条件:升序数组;
结果:找得到的话返回 数组下标,找不到则返回 -1 ;
循环
//二分查找-循环(升序数组) int binarySearch(vector<int>& nums, int target) { int start = 0, end = nums.size() - 1, mid = 0; while (start <= end) { //mid=(start+end)/2; //可以用这个,但是 "start+end" 有可能会造成溢出 mid = start + (end - start) / 2; if (nums[mid] == target) return mid; else if (nums[mid] > target) end = mid - 1; else start = mid + 1; } return -1; }
递归
int search(vector<int>& nums, int target) { return binarySearch(nums, target, 0, nums.size() - 1); } //二分查找-递归(升序数组) int binarySearch(vector<int>& nums, int target, int start, int end) { if (start > end) return -1; int mid = (start + end) / 2; if (nums[mid] == target) return mid; else if (nums[mid] > target) //大于目标,则需要往前找 return binarySearch(nums, target, start, mid - 1); else //小于目标,则需往后找 return binarySearch(nums, target, mid + 1, end); }
三个部分
- 终止条件;
- 中间值是否符合;
- 继续查找;