C++ 非递归二分搜索算法实现 - 详细代码示例
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 6;
int index = binarySearch(arr, n, target);
if (index != -1)
cout << 'Target found at index ' << index << endl;
else
cout << 'Target not found' << endl;
return 0;
}
本代码实现了一个非递归的二分搜索算法。该算法首先定义左右边界left和right,并不断缩小搜索范围。在每次循环中,计算中间位置mid,并比较arr[mid]与目标值target。如果相等,则返回mid。如果arr[mid]小于target,则将left移到mid + 1,否则将right移到mid - 1。如果循环结束后未找到target,则返回-1。
本代码示例展示了如何使用C++实现非递归二分搜索算法。您可以根据自己的需求修改代码,例如更改数组内容或目标值。二分搜索算法是一种高效的查找算法,可以快速找到排序数组中的目标值。
原文地址: https://www.cveoy.top/t/topic/n8HM 著作权归作者所有。请勿转载和采集!