折半查找非递归算法
#include<iostream>
using namespace std;
int BinSearch(int arr[], int n, int target)
{
int l = 0, r = n - 1;
while (l <=r )
{
int mid = l + (r - l) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
int main()
{
int a[10] = { 1,2,3,4,5,6,7,8,9,10 };
int res = BinSearch(a, 10, 3);
cout << res << endl;
return 0;
}
本文深入探讨了折半查找算法的非递归实现方式,通过详细的代码示例展示了如何在一个有序数组中查找特定元素的位置。文章提供了完整的C++代码实现,并通过一个具体的查找任务演示了算法的工作流程。
2624

被折叠的 条评论
为什么被折叠?



