We, beginners, should help each other.:)
Here you are.
As you specified the language tags C and C++ then the demonstration program below can be run in C and C++. That is there are no special features of C++ except using names bool
, false
and true
that in C can be used if to include header <stdbool.h>
Also in C you need to include header <stdio.h>
instead of <iostream>
#include <iostream>
size_t binary_search( const int a[], size_t n, int value )
{
size_t left = 0, right = n, middle = 0;
bool found = false;
while ( !found && left != right )
{
middle = left + ( right - left ) / 2;
if ( value < a[middle] )
{
right = middle;
}
else if ( a[middle] < value )
{
left = middle + 1;
}
else
{
found = true;
}
}
return found ? middle : -1;
}
int main( void )
{
int a[] = { 1, 3, 5, 7, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( int value = 0; value <= a[N - 1] + 1; value++ )
{
size_t pos = binary_search( a, N, value );
if ( pos != -1 )
{
printf( "%d is found at %zu.\n", value, pos );
}
else
{
printf( "%d is not found.\n", value );
}
}
}
The program output is
0 is not found.
1 is found at 0.
2 is not found.
3 is found at 1.
4 is not found.
5 is found at 2.
6 is not found.
7 is found at 3.
8 is not found.
9 is found at 4.
10 is not found.
Pay attention to that in general in C++ you will need to write a template function while in C you will write the function similarly to the implementation of bsearch
.
Without using the variable found
the function can look as
size_t binary_search( const int a[], size_t n, int value )
{
size_t left = 0, right = n;
while ( left != right )
{
size_t middle = left + ( right - left ) / 2;
if ( value < a[middle] )
{
right = middle;
}
else if ( a[middle] < value )
{
left = middle + 1;
}
else
{
return middle;
}
}
return -1;
}