1. 二分查找
//递归版 int binarySearch(const int arr[], int low, int high, int val) { if (low <= high) { int mid = low + (high - low) / 2; // Do not use (low + high) / 2 which might encounter overflow issue if (val < arr[mid]) return binarySearch(arr, low, mid-1, val); else if (val > arr[mid]) return binarySearch(arr, mid+1, high, val); else return mid; } return -1; } //非递归版 int binarySearch(const int arr[], int low, int high, int val) { while (low <= high) { int mid = low + (high - low) / 2; // Do not use (low + high) / 2 which might encounter overflow issue if (val < arr[mid]) high = mid - 1; else if (val > arr[mid]) low = mid + 1; else return mid; } return -1; }
时间: 2024-10-31 14:50:07