#include<iostream>
using namespace std;
#define TT_ERROR -1
int binary_search(int arr[], int array_size, int key)
{
if ((arr == nullptr) || (array_size == 0))
{
return TT_ERROR;
}
int left(0); //数组的首位置,即data[0]处
int right = array_size - 1; //数组的最后一个位置,即data[n-1],数组大小为array_size
while (left <= right)
{
//int mid = (left + right) / 2;//array_size为偶数,取靠左的那个(当left和right比较大时,二者之和可能会溢出)
int mid = left + ((right - left) >> 1);/*此处的mid的计算一定要放在while循环内部,
否则mid无法正确更新;并且此处用移位代替除以2可以提高效率,
而且可以防止溢出。*/
if (arr[mid] > key)
{
right = mid - 1;
}
else if (arr[mid] < key)
{
left = mid + 1;
}
else
{
return mid;
}
}
return TT_ERROR;
}
int main()
{
while (true)
{
{
cout << "\n************************欢迎来到来到二分查找的世界!**********************\n" << endl
<< "输入0,退出程序!" << endl
<< "输入1,进行二分查找!" << endl
<< "输入2,清屏!" << endl;
}
cout << "\n请输入你的选择:";
int choice(0);
cin >> choice;
if (choice == 0)
{
cout << "程序已退出!" << endl;
break;
}
switch (choice)
{
case 1:
{
cout << "请输入你想要查找元素列表的长度:";
int list_Length(0);
cin >> list_Length;
int *array = new int[list_Length];
for (int i = 0; i < list_Length; ++i)
{
cin >> array[i];
}
;
int element(0), locate(0);
cout << "请输入你想要在数组中查找的元素是:";
cin >> element;
if ((locate = binary_search(array, list_Length, element)) >= 0)
{
cout << "找到元素" << element << ",它在数组中的位置为:" << locate << endl;
}
else
cout << "没有找到你想要查找的元素" << element << "!" << endl;
delete[]array;
array = nullptr;
break;
}
case 2:
system("cls");
cout << "屏幕已清屏,可以重新输入!" << endl;
break;
default:
cout << "序号输入错误,请重新输入!" << endl;
}
}
system("pause");
return 0;
}
折半(二分)查找的c++代码(递归和非递归)实现
5星 · 超过95%的资源 需积分: 47 171 浏览量
2017-05-12
15:03:34
上传
评论
收藏 2KB ZIP 举报
To-String
- 粉丝: 216
- 资源: 36
最新资源
- tensorflow-rocm-2.12.0.560-cp311-cp311-manylinux2014-x86-64.whl
- Windows操作系统中的CMD(命令提示符).md
- tensorflow-rocm-2.12.0.560-cp39-cp39-manylinux2014-x86-64.whl
- mmexport1713512496118.jpg
- 基于VB的俄罗斯方块系统设计与实现(源代码+参考文献).zip
- 软件测试开发工具大全资源包之Linux虚拟机
- python毕设-图片批量处理器
- 基于VB的教材管理系统设计(源代码+系统+报告+PPT).zip
- Lock接口与synchronized关键字
- 基于Java的图书馆自习室座位预约系统设计源码
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈