Binary Search in C++ Standard Template Library

Binary search is a widely used searching algorithm that requires the array to be sorted before search is applied.

The prototype for binary search is :

binary_search(startaddress, endaddress, valuetofind)
#include <iostream>
#include <algorithm>

using namespace std;

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


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

    cout << "\n\nLet's say we want to search for 2 in the array";
    cout << "\n So, we first sort the array";
    sort(a, a + 10);
    cout << "\n\n The array after sorting is : ";
    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;

}

The output of the above program is :

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

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar