几种典型查找算法的实现 编程实现:利用折半查找算法实现在数据序列{2,3,6,33,45,66,88,100}分别查找关键字6和89的结果,找到输出位序,找不到输出相应提示信息。vs2010
时间: 2023-08-03 18:05:20 浏览: 107
以下是利用折半查找算法实现在数据序列{2,3,6,33,45,66,88,100}分别查找关键字6和89的代码:
```c++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int key)
{
int left = 0, right = n - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] == key)
{
return mid;
}
else if (arr[mid] > key)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return -1;
}
int main()
{
int arr[] = {2, 3, 6, 33, 45, 66, 88, 100};
int n = sizeof(arr) / sizeof(arr[0]);
int key1 = 6;
int index1 = binarySearch(arr, n, key1);
if (index1 != -1)
{
cout << "关键字 " << key1 << " 的位置是:" << index1 << endl;
}
else
{
cout << "未找到关键字 " << key1 << endl;
}
int key2 = 89;
int index2 = binarySearch(arr, n, key2);
if (index2 != -1)
{
cout << "关键字 " << key2 << " 的位置是:" << index2 << endl;
}
else
{
cout << "未找到关键字 " << key2 << endl;
}
return 0;
}
```
输出结果为:
```
关键字 6 的位置是:2
未找到关键字 89
```
阅读全文