双调数组中的二分查找
双调数组是指所有元素先递增后递减的数组,对其进行二分查找时,应先用二分查找找出数组中的最大项,再对左右两个单调子数组进行二分查找。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | Item BitonicSearch(Item bitonicArray[], int length, int searchKey) { if ((bitonicArray == NULL) || (lenght <= 0)) { return NULLItem; } int indexOfMaxItem = GetIndexOfMaxItem(bitonicArray,length); // 获取针对双调数组的递增部分的搜索结果 Item result = BinarySearch(bitonicArray,0,indexOfMaxItem,searchKey); if (result == NULLItem) { // 获取针对双调数组的递减部分的搜索结果 result = BinarySearch(bitonicArray,indexOfMaxItem + 1,length - 1,searchKey); } return result; } int GetIndexOfMaxItem(Item bitonicArray[], int length) { int low = 0; int high = length - 1; int middle; while (low < high) { middle = (low + high) / 2; // 检查bitonicArray[middle + 1]是否处于双调数组的递增部分中 if (bitonicArray[middle] < bitonicArray[middle + 1]) { // 如果处于,则数组的最大项的索引必不小于middle + 1 low = middle + 1; } else { // 如果不处于,则数组的最大项的索引必不大于middle high = middle; } } // 此时low = high return low; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步