二分查找算法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include
#include
#include
#include
#include
const int N = 1001; // 数组元素数目
float count=0.0;
float RowCount=0.0;
using namespace std;
// 声明二分查找算法
int binarySearch( const int b[], int searchKey, int low, int high );
int main() {
int array[N];
int SearchTimes = 10; // SearchTimes: 重复查找每个数组次数
srand(time(0)); // 随机数发生器的初始化函数,使每次产生的随机数不同
cout << "Every array repeat search times: " << SearchTimes << endl;
cout << "Number of Elements" << setw(18) << "理论平均查找次数" << setw(22) << "实际平均查找次数" << endl;
for ( int j=100; j <=1000; j+=100 ) {
array[0]=10+rand()%15;
for(int i=1; i // 生成递增随机数列 array[i]=array[i-1]+1+rand()%3+rand()%10; } // SearchTimes: 重复查找每个数组次数 // C 语言是大小写敏感的 for (int time=0; time < SearchTimes; time++) { // suffix 为要搜索的元素下标 int suffix = rand() % j; // key 为要查找的数据 int key = array[suffix]; int result = binarySearch( array, key, 0, j-1 ); } count = (RowCount / SearchTimes ); RowCount = 0.0; // 输出 // Function log() 默认以E为底so 用换底公式搞定 cout << setw(18) << j << setw(18) << int( log(j)/log(2) ) + 1.0/2 << setw(22) << count << endl; count=0.0; // 令全局变量为0 } return 0; } /////////////////////////////////////////////////////////////////////////// // BinarySearch int binarySearch( const int b[], int searchKey, int low, int high ) { int middle; while( low <= high ) { middle = ( low + high ) / 2; if (searchKey == b[middle]) { RowCount++; return middle; } else if ( searchKey < b[middle] ) { high = middle - 1; RowCount++; } else { low = middle + 1; RowCount++; } } return -1; // not found }