STL-03 Binary Search in C++ Standard Template Library

Binary Search in C++ Standard Template Library (STL)

Binary search is a widely used searching algorithm that requires the array to be sorted before search is applied. The main idea behind this algorithm is to keep dividing the array in half (divide and conquer) until the element is found, or all the elements are exhausted.
It works by comparing the middle item of the array with our target, if it matches, it returns true otherwise if the middle term is greater than the target, the search is performed in the left sub-array. If the middle term is less than the target, the search is performed in the right sub-array.

The prototype for binary search is :

binary_search(startaddress, endaddress, valuetofind)

Parameters :
startaddress: the address of the first element of the array.
endaddress: the address of the next contiguous location of 
            the last element of the array.
valuetofind: the target value which we have to search for.

Returns :
true if an element equal to valuetofind is found, else false.

An Example for binary_search

// CPP program to implement Binary Search in Standard Template Library (STL) 
#include <algorithm> 
#include <iostream> 

using namespace std; 

void show(int a[], int arraysize) { 
	for (int i = 0; i < arraysize; ++i) 
		cout << a[i] << ","; 
} 

int main() { 
	int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; 
	int asize = sizeof(a) / sizeof(a[0]); 
	cout << "\nThe array is : \n"; 
	show(a, asize); 

	cout << "\n\nLet's say we want to search for "; 
	cout << "\n2 in the array So, we first sort the array"; 
	sort(a, a + asize); 
	cout << "\n\nThe array after sorting is : \n"; 
	show(a, asize); 
	cout << "\n\nNow, we do the binary search"; 
	if (binary_search(a, a + 10, 2)) 
		cout << "\nElement found in the array"; 
	else
		cout << "\nElement not found in the array"; 

	cout << "\n\nNow, say we want to search for 10"; 
	if (binary_search(a, a + 10, 10)) 
		cout << "\nElement found in the array"; 
	else
		cout << "\nElement not found in the array"; 

	return 0; 
}

Output

The array is : 
1,5,8,9,6,7,3,4,2,0,

Let's say we want to search for 
2 in the array So, we first sort the array

The array after sorting is : 
0,1,2,3,4,5,6,7,8,9,

Now, we do the binary search
Element found in the array

Now, say we want to search for 10
Element not found in the array

More details on std::bsearch in C++ STL

std::bsearch searches for an element in a sorted array. Finds an element equal to element pointed to by key in an array pointed to by ptr.
If the array contains several elements that comp would indicate as equal to the element searched for, then it is unspecified which element the function will return as the result.

Syntax :

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.

Implementing the binary predicate 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"; 
} 

Output:

4 found at position 3
9 not found

Where to use :

Binary search can be used on sorted data where a key is to be found. It can be used in cases like computing frequency of a key in a sorted list.

Why Binary Search?

Binary search is much more effective than linear search because it halves the search space at each step. This is not significant for our array of length 9. Here, linear search takes at most 9 steps and binary search takes at most 4 steps. But consider an array with 1000 elements, here linear search takes at most 1000 steps, while binary search takes at most 10 steps.
For 1 billion elements, binary search will find our key in at most 30 steps.

More about c++ STL, turn to this page.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值