当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ std::bsearch用法及代码示例


二进制搜索基础

std::bsearch在排序数组中搜索元素。在ptr指向的数组中查找与key指向的元素相等的元素。
如果数组包含comp表示与搜索到的元素相等的多个元素,则未指定函数将作为结果返回的元素。
用法:

void* bsearch( const void* key, const void* ptr, std::size_t count,
               std::size_t size, * comp );

参数:
key     -    element to be found
ptr     -    pointer to the array to examine
count    -    number of element in the array
size    -    size of each element in the array in bytes
comp    -    comparison function which returns ?a negative integer value if 
             the first argument is less than the second,
             a positive integer value if the first argument is greater than the second
             and zero if the arguments are equal.

返回值:
Pointer to the found element or null pointer if the element has not been found.

实现二进制谓词comp:


// Binary predicate which returns 0 if numbers found equal 
int comp(int* a, int* b) 
{ 
  
    if (*a < *b) 
        return -1; 
  
    else if (*a > *b) 
        return 1; 
  
    // elements found equal 
    else
        return 0; 
}

Implementation

// CPP program to implement 
// std::bsearch 
#include <bits/stdc++.h> 
  
// Binary predicate 
int compare(const void* ap, const void* bp) 
{ 
    // Typecasting 
    const int* a = (int*)ap; 
    const int* b = (int*)bp; 
  
    if (*a < *b) 
        return -1; 
    else if (*a > *b) 
        return 1; 
    else
        return 0; 
} 
  
// Driver code 
int main() 
{ 
    // Given array 
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; 
  
    // Size of array 
    int ARR_SIZE = sizeof(arr) / sizeof(arr[0]); 
  
    // Element to be found 
    int key1 = 4; 
  
    // Calling std::bsearch 
    // Typecasting the returned pointer to int 
    int* p1 = (int*)std::bsearch(&key1, arr, ARR_SIZE, sizeof(arr[0]), compare); 
  
    // If non-zero value is returned, key is found 
    if (p1) 
        std::cout << key1 << " found at position " << (p1 - arr) << '\n'; 
    else
        std::cout << key1 << " not found\n"; 
  
    // Element to be found 
    int key2 = 9; 
  
    // Calling std::bsearch 
    // Typecasting the returned pointer to int 
    int* p2 = (int*)std::bsearch(&key2, arr, ARR_SIZE, sizeof(arr[0]), compare); 
  
    // If non-zero value is returned, key is found 
    if (p2) 
        std::cout << key2 << " found at position " << (p2 - arr) << '\n'; 
    else
        std::cout << key2 << " not found\n"; 
}

输出:

4 found at position 3
9 not found

使用位置:二进制搜索可用于要查找关键字的已排序数据。它可以用于诸如排序列表中键的计算频率之类的情况。

为什么选择二进制搜索?
二进制搜索比线性搜索更有效,因为它使每一步的搜索空间减半。这对于长度为9的数组而言并不重要。这里,线性搜索最多需要9个步骤,而二进制搜索最多需要4个步骤。但是考虑具有1000个元素的数组,此处线性搜索最多需要1000步,而二进制搜索最多需要10步。
对于10亿个元素,二进制搜索最多可以在30个步骤中找到我们的关键字。



相关用法


注:本文由纯净天空筛选整理自 std::bsearch in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。