📜  C++中的std :: bsearch

📅  最后修改于: 2021-05-30 04:37:51             🧑  作者: Mango

二元搜索基础

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

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

Parameters :
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.

Return value :
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;
}

执行

// CPP program to implement
// std::bsearch
#include 
  
// 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个步骤中找到我们的关键字。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”