21xrx.com
2024-05-20 07:29:07 Monday
登录
文章检索 我的文章 写文章
C++实现二分查找及输出代码
2023-07-06 05:40:14 深夜i     --     --
C++ 二分查找 实现 代码 输出

二分查找,也称为折半查找,是一种常见的查找算法。与顺序查找相比,二分查找的时间复杂度为O(log n),适用于已经排好序的数组。

在C++中,实现二分查找需要使用二分查找函数,它可以返回目标元素在数组中的位置。以下是实现二分查找的C++代码:


#include <iostream>

using namespace std;

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) {

      left = mid + 1;

    } else

      right = mid - 1;

    

  }

  return -1;

}

int main() {

  int arr[] = 3;

  int n = sizeof(arr) / sizeof(arr[0]);

  int target = 7;

  int index = binarySearch(arr, 0, n - 1, target);

  if (index != -1)

    cout << "The target " << target << " is found at index " << index << endl;

   else

    cout << "The target " << target << " is not found in the array." << endl;

  

  return 0;

}

在上述代码中,我们定义了一个`binarySearch()`函数,该函数接收以下参数:

- `arr[]`:代表数组元素;

- `left`:代表左边的元素下标;

- `right`:代表右边的元素下标;

- `target`:代表查找的目标元素。

在函数内部,通过while循环不断缩小查找范围,最终找到目标元素并返回其下标,或者没有找到目标元素并返回-1。

在`main()`函数中,定义了一个整型数组`arr[]`和一个目标元素`target`,然后通过调用`binarySearch()`函数进行二分查找。根据返回值,输出查找结果。

总结来说,C++实现二分查找需要定义二分查找函数,并通过循环不断调整查找范围,最终返回目标元素的位置或-1。二分查找实现起来比较简单,但可以大大提高查找效率,适用于各种类型的数据结构。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复