首页 > 编程语言 >【算法-二分查找】实现过程、C++代码示例以及实际应用

【算法-二分查找】实现过程、C++代码示例以及实际应用

时间:2023-08-26 11:00:29浏览次数:58  
标签:二分 cur 示例 int mid value pos C++ 目标值

二分查找简介:

也称为折半查找,是一个在已排序数组中查找特定元素的搜索算法。它的工作原理是将有序数组分成两半,然后检查目标值是在左半部分还是右半部分,然后在所选择的那部分中继续查找。这一过程将不断地重复,直到找到目标值或确定目标值不在数组中。

实现过程:

1.初始化两个指针:low 设置为数组的开始位置,high 设置为数组的结束位置。
2.当 low 不大于 high 时,执行以下操作:
-计算中间位置 mid
-如果 array[mid] 是目标值,则返回 mid 位置。
-如果 array[mid] 小于目标值,设置 low 为 mid + 1。
-否则,设置 high 为 mid - 1。
3.如果循环结束还没有返回,那么目标值不在数组中,返回 -1 或其他表示“不在数组中”的值。

一份C++的二分示例如下:

#include <iostream>
#include <vector>

template<typename T>
int binarySearch(const std::vector<T>& sortedArr, T target) {
    int low = 0;
    int high = sortedArr.size() - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (sortedArr[mid] == target) {
            return mid;  // 找到目标值,返回其索引
        }
        if (sortedArr[mid] < target) {
            low = mid + 1;  // 查找数组的右侧部分
        } else {
            high = mid - 1;  // 查找数组的左侧部分
        }
    }

    return -1;  // 如果数组中不存在目标值,则返回-1
}


/* compile : g++ binarySerach.cpp -std=c++11 */
int main() {
    std::vector<int> sortedArr {1, 2, 4, 5, 6, 8, 9, 11, 13, 15};

    int target = 9;
    int result = binarySearch(sortedArr, target);

    if (result != -1) {
        std::cout << "Element " << target << " found at index: " << result << std::endl;
    } else {
        std::cout << "Element " << target << " not found in the array." << std::endl;
    }

    return 0;
}

实际应用如redis源码 intset.c

/* Search for the position of "value". Return 1 when the value was found and
 * sets "pos" to the position of the value within the intset. Return 0 when
 * the value is not present in the intset and sets "pos" to the position
 * where "value" can be inserted. */
static uint8_t intsetSearch(intset *is, int64_t value, uint32_t *pos) {
    int min = 0, max = intrev32ifbe(is->length)-1, mid = -1;
    int64_t cur = -1;

    /* The value can never be found when the set is empty */
    if (intrev32ifbe(is->length) == 0) {
        if (pos) *pos = 0;
        return 0;
    } else {
        /* Check for the case where we know we cannot find the value,
         * but do know the insert position. */
        if (value > _intsetGet(is,max)) {
            if (pos) *pos = intrev32ifbe(is->length);
            return 0;
        } else if (value < _intsetGet(is,0)) {
            if (pos) *pos = 0;
            return 0;
        }
    }

    while(max >= min) {
        mid = ((unsigned int)min + (unsigned int)max) >> 1;
        cur = _intsetGet(is,mid);
        if (value > cur) {
            min = mid+1;
        } else if (value < cur) {
            max = mid-1;
        } else {
            break;
        }
    }

    if (value == cur) {
        if (pos) *pos = mid;
        return 1;
    } else {
        if (pos) *pos = min;
        return 0;
    }
}

标签:二分,cur,示例,int,mid,value,pos,C++,目标值
From: https://www.cnblogs.com/dujn/p/17658502.html

相关文章

  • C++STL函数
    1、排序算法描述键盘输入5个整数,使用vector进行存储,使用STL排序算法对元素进行排序(从大到小),再使用STL遍历算法输出元素。(元素和元素之间使用空格隔开)输入描述:键盘输入5个整数输出描述:输出排序后的元素,元素和元素之间使用空格隔开。#include<iostream>#include<ve......
  • 《C++》C11新特性--1
    1.原始字符串字面量R"(字符串)"constchar*str1="D:hello\world\test.txt";constchar*str2=R"(D:hello\world\test.txt)";std::cout<<"直接输出str:\t\t"<<str1<<std::endl;std::cout<......
  • 字符串处理C++
    1、字符串连接题目描述不借用任何字符串库函数实现无冗余地接受两个字符串,然后把它们无冗余的连接起来。输入每一行包括两个字符串,长度不超过100。输出可能有多组测试数据,对于每组数据,不借用任何字符串库函数实现无冗余地接受两个字符串,然后把它们无冗余的连接起来。输出连接......
  • android 添加多个c++文件并 调用c++打印调试信息
    首先在gradle文件中配置cmake:注意文件路径一定要对应上android{//...defaultConfig{//...externalNativeBuild{cmake{cppFlags"-frtti-fexceptions-Wno-deprecated-declarations"......
  • C++之运算符
    运算符函数在C++中会把运算符当做函数处理,一个表达式,其实可能调用了很多运算符函数来完成计算,这种特性对内建类型没有用,但是对于自建类型而言,通过设计运算符函数能够进行个性化运算,以此提高代码的可读性、易用性,例如string类Ⅰ.运算符函数的格式:'#'表示运算符,'O'表示运算符对......
  • linux docker公网源下载示例
    1.get-docker.sh百度一下,进入docker官网直接下载该文件,然后执行即可2.直接下载repo文件示例:wgethttps://download.docker.com/linux/centos/docker-ce.repo-O/etc/yum.repos.d/docker.sh--no-check或者yum-config-manager--add-repohttps://download.docker.com/lin......
  • 算法 -- 二分查找
    力扣题目链接给定一个n个元素有序的(升序)整型数组nums和一个目标值target,写一个函数搜索nums中的target,如果目标值存在返回下标,否则返回-1。示例1:输入:nums=[-1,0,3,5,9,12],target=9输出:4解释:9出现在nums中并且下标为4示例2:输入:nums=[-1......
  • C++单例模式
    单例模式什么是单例模式:只能实例化一个类对象(全局有且只有一个类的static实例)使用场景:进程管理器、日志管理器、网站访问计数器、应用配置程序、线程池、服务器的连接管理器实现单例模式的原理/步骤1、禁止在类外随意实例化对象,把构造函数/拷贝构造都私有化private2、确保......
  • c++ stl std::sort使用例子
    classUser{public:int32_tm_fight_power;private:int32_tm_level;};boolCenterData::compare(constUser*left,constUser*right){if(left->m_fight_power!=right->m_fight_power){returnleft->m_fight_power>ri......
  • C++异常处理:try、throw、catch
    ​1.引子程序在运行时,总是会遇到一些错误,这些错误或者是导致程序无法运行,例如操作空指针,或是不符合正常运行的规律,例如除以0。因此,在C++程序当中就必须添加对应异常处理机制,在检测到指定的程序异常时,为保证程序正常运行,需要跳转至异常处理程序当中。常规的错误处理有以下几种解......