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

C++Server Side ProgrammingProgramming

A binary search known as logarithmic search is a search algorithm that searches for an element in a sorted array. The algorithm recursively divides the array into two halves, if the element is found at the mid position then return otherwise call the divide and check again until the element is found.

Working

The algorithm works by comparing the middle element of the sorted array with the element that is to be searched.

If the search element is equal to the middle element, then return the index of the element.

If the search element is greater than the middle element, search in the left subarray i.e. sub array from the next element of the middle to the end of the array.

If the search element is lesser than the middle element, search in right sub array i.e. sub array from the first element to the element preceding the middle of the array.

Syntax

The call to standard binary sort, the following syntax is used −

binary_search(start_address , end_address , element)

Parameter

start_address is the address of the first element of the array.

end_address is the address of the last element of the array.

element is the element to be found in the array.

Return

It returns an integer whose value is equal to the index of the element in the array if found otherwise returns 0.

Example

 Live Demo

#include <algorithm>
#include <iostream>
using namespace std;
void printArray(int a[], int arraysize){
   for (int i = 0; i < arraysize; ++i)
      cout << a[i] << " ";
}
int main(){
   int arr[] = {1 , 5, 9, 7 , 3, 2 , 0 , 4};
   int sizeofarr = sizeof(arr)/sizeof(arr[0]);
   cout<<"The Element of array are :\n";
   printArray(arr , sizeofarr);
   cout<<"\nSorting Elements of array.";
   sort(arr , arr+sizeofarr);
   cout<<"\nSorted array is : ";
   printArray(arr, sizeofarr);
   cout<<"\nElement to be searched is 4";
   if(binary_search(arr , arr+sizeofarr , 4))
      cout<<"\nElement found ";
   else
      cout<<"\nElement not found";
}

Output

The Element of array are :
1 5 9 7 3 2 0 4
Sorting Elements of array.
Sorted array is : 0 1 2 3 4 5 7 9
Element to be searched is 4
raja
Published on 03-Jan-2020 06:19:20
Advertisements