C++二分查找(折半查找)递归算法详解
发布时间:2020-12-16 07:37:10 所属栏目:百科 来源:网络整理
导读:前面介绍过二分查找算法,以及如何使用它来查找给定值的排序数组,本节来看一看如何使用递归实现二分查找算法。 假设要编写一个函数,其函数原型如下: int binarySearch(const int array[],int first,int last,int value) 其中,形参 array 是要查找的数组,
前面介绍过二分查找算法,以及如何使用它来查找给定值的排序数组,本节来看一看如何使用递归实现二分查找算法。 假设要编写一个函数,其函数原型如下: int binarySearch(const int array[],int first,int last,int value) 其中,形参 array 是要查找的数组,形参 first 保存了查找范围(即要查找的数组的一部分)中第一个元素的下标;形参 last 保存了查找范围中最后一个元素的下标;形参 value 保存了要查找的值。如果在数组中找到了 value,则该函数将返回 value 的下标,否则返回 -1。要使用递归,则需要找到一种方法,将在已排序数组的一定范围内查找给定值的问题分解成相同类型的小问题。首先从比较 value 与查找范围的中间元素开始:
请注意,每次进行递归调用时,查找范围都会变小。基本情况是当查找范围为空时。以下是该函数代码: int binarySearch(const int array[],int value) { int middle; //查找的中间点 if (first > last) // 基本情况 return -1; middle = (first + last) / 2; if (array[middle] == value) return middle; if (array[middle] < value) return binarySearch(array,middle+1,last,value); else return binarySearch(array,first,middle-1,value); }下面的程序演示了该函数: //This program demonstrates a recursive function that performs a binary search on an integer array. #include <iostream> using namespace std; //Function prototype int binarySearch(const int array[],int value); const int SIZE = 20; int main() { int tests[SIZE] = {101,142,147,189,199,207,222,234,289,296,310,319,388,394,417,429,447,521,536,600}; int result; // Result of the search int empID; // What to search for cout << "Enter the Employee ID you wish to search for: "; cin >> empID; result = binarySearch(tests,SIZE-1,empID); if (result == -1) cout << "That number does not exist in the array.n"; else { cout << "That ID is found at element " << result; cout << " in the arrayn"; } return 0; } int binarySearch(const int array[],int value) { int middle; // Mid point of search if (first > last) // Base case return -1; middle = (first + last)/2; if (array[middle]==value) return middle; if (array[middle]<value) return binarySearch(array,value); else return binarySearch (array,value); }程序输出结果:
Enter the Employee ID you wish to search for: 521 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- WebLogic 10.3 server failed:Failure in config
- Vuejs第六篇之Vuejs与form元素实例解析
- 使用正则表达式实现一个简单的QQ登录验证
- 前端解析后台返回的JSONArray字符串
- postgresql – 如何更改Postgres中的默认client_
- Dagger - 快速依赖注入器(for android and java)
- iphone – AVSpeechSynthesizer问题的iOS9 AVSpe
- c# – EventHandle.WaitOne WebBrowser =等待Doc
- On Story Estimation: 单一职责原则
- xcode – Swift导入语句不再需要
热点阅读