In computer science, binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array.
The code returns true if an element is present in the array else returns false.
Any suggestion in improving the code is welcome.
Binary_Search.h
#ifndef BINARY_SEARCH_H
#define BINARY_SEARCH_H
bool binary_search(int ar[], int low, int high, int key);
#endif // BINARY_SEARCH_H
Binary_Search.cpp
#include <iostream>
#include "Binary_Search.h"
/* search a key in an array using binary search */
bool binary_search(int ar[], int low, int high, int key)
{
int mid;
while ( low <= high )
{
// find the middle index
mid = low + ((high - low) >> 1);
if ( ar[mid] == key ) // key found
{
return true;
}
else if ( ar[mid] > key ) // key may be on the left half
{
high = mid - 1;
}
else if ( ar[mid] < key ) // key may be on the right half
{
low = mid + 1;
}
}
// key not found
return false;
}
int main()
{
int ar[] = {1, 7, 9, 10, 28, 28, 36, 49, 68, 99};
for ( int i = 0; i < sizeof(ar) / sizeof(ar[0]); ++i )
{
if ( binary_search(ar, 0, sizeof(ar) / sizeof(ar[0]) - 1, ar[i]) )
{
std::cout << ar[i] << " is present" << std::endl;
}
else
{
std::cout << ar[i] << " is not present" << std::endl;
}
}
int ar1[] = {-1, 2, 3, 12, 23, 50, 90, 98, 100};
for ( int i = 0; i < sizeof(ar1) / sizeof(ar1[0]); ++i )
{
if ( binary_search(ar, 0, sizeof(ar) / sizeof(ar[0]) - 1, ar1[i]) )
{
std::cout << ar1[i] << " is present" << std::endl;
}
else
{
std::cout << ar1[i] << " is not present" << std::endl;
}
}
return 0;
}
emacs
gives that kind of formatting. I don't know whether that is good or not \$\endgroup\$emacs
applies. \$\endgroup\$