【数据结构/C++】二分查找

二分查找:根据索引二分,循环查找的条件是左索引小于等于右索引。

二叉树需要判断自身根是否为NULL,并通过改变current的值进行判断。

#include <iostream>
using namespace std;
// 长度为 N 的有序表nums 中查找 target
int BiSearch(int *nums, int N, int target)
{
   
  int l = 0, r = N - 1;
  while (l <= r)
  {
   
    int mid = (l + r) / 2;
    if (target == nums[mid])
    {
   
      return mid;
    }
    if (target < nums[mid])
    {
   
      r = mid - 1;
    }
    if (target > nums[mid])
    {
   
      l = mid + 1;
    }
  }
  return -1;
}
// 二叉树
typedef struct TreeNode
{
   
  int data;
  struct TreeNode *left, *right;
} TreeNode;
TreeNode *SearchTree(TreeNode *root, int target)
{
   
  if (!root)
  {
   
    return NULL;
  }
  TreeNode *current = root;
  while (current)
  {
   
    if (target == current->data)
    {
   
      return current;
    }
    if (target < current->data)
    {
   
      current = current->left;
    }
    else
    {
   
      current = current->right;
    }
  }
  return NULL;
}
int main()
{
   
  int nums[10] = {
   1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
  cout << BiSearch(nums, 10, 5) << endl;
  return 0;
}

相关推荐

  1. 数据结构/C++】二分查找

    2023-12-10 23:30:02       37 阅读
  2. 数据结构-二分查找

    2023-12-10 23:30:02       22 阅读
  3. C语言----数组----二分查找

    2023-12-10 23:30:02       13 阅读
  4. 刷题 数组-二分查找C++

    2023-12-10 23:30:02       9 阅读
  5. c++】二分查找教程

    2023-12-10 23:30:02       38 阅读
  6. C++二分查找

    2023-12-10 23:30:02       36 阅读
  7. C语言-二分查找

    2023-12-10 23:30:02       26 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-10 23:30:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-10 23:30:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-10 23:30:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-10 23:30:02       20 阅读

热门阅读

  1. idea连接Hbase卡住,没有输出

    2023-12-10 23:30:02       38 阅读
  2. ES6中的Set

    2023-12-10 23:30:02       37 阅读
  3. LinuxBasicsForHackers笔记 --添加和删除软件

    2023-12-10 23:30:02       32 阅读
  4. Qt 通过命令行编译程序

    2023-12-10 23:30:02       41 阅读
  5. qt5图形视频框架

    2023-12-10 23:30:02       36 阅读
  6. Linux指令——scp:传输文件

    2023-12-10 23:30:02       43 阅读
  7. kafka

    2023-12-10 23:30:02       40 阅读
  8. LeetCode 76. 最小覆盖子串 滑动窗口框架

    2023-12-10 23:30:02       43 阅读
  9. python函数

    2023-12-10 23:30:02       42 阅读
  10. Python大数据之Python进阶(三)多进程的使用

    2023-12-10 23:30:02       39 阅读