酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

c++写二分查找

以下是一个使用 C++ 实现二分查找的示例代码: ```cpp #include <iostream> // 二分查找函数 int binarySearch(int arr[], int left, int right, int target) { while (left <= right) { int mid = left + (right - left) / 2; // 找到目标元素 if (arr[mid] == target) { return mid; } // 目标在左半部分 else if (arr[mid] > target) { right = mid - 1; } // 目标在右半部分 else { left = mid + 1; } } // 未找到目标元素 return -1; } int main() { int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; int target = 12; int result = binarySearch(arr, 0, sizeof(arr) / sizeof(arr[0]) - 1, target); if (result!= -1) { std::cout << "元素 " << target << " 在数组中的索引为 " << result << std::endl; } else { std::cout << "数组中未找到元素 " << target << std::endl; } return 0; } ``` 在上述代码中,`binarySearch` 函数接受一个已排序的整数数组、左右边界索引和目标值作为参数,并通过不断将数组中间元素与目标值比较来缩小查找范围,最终返回目标值在数组中的索引,如果未找到则返回 `-1`。在 `main` 函数中,我们创建了一个示例数组并调用 `binarySearch` 函数进行查找。 [2024-09-19 10:55:14 | AI写代码神器 | 418点数解答]

相关提问