當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。