binary_search.cpp File Reference

Binary search algorithm More...

`#include <iostream>`
Include dependency graph for binary_search.cpp:

## Functions

int | binary_search (int a[], int r, int key)
int | main (int argc, char const *argv[])

## Detailed Description

Binary search algorithm

## Function Documentation

## binary_search()

int binary_search | ( | int | a[],
|  | int | r,
|  | int | key
| ) |  |

binary_search function

Parameters

  [in] | a | array to sort
  [in] | r | right hand limit = \(n-1\)
  [in] | key | value to find

Returns
  index if T is found
  -1 if T is not found

{
int l = 0;
while (l <= r) {
int m = l + (r - l) / 2;
if (key == a[m])
return m;
else if (key < a[m])
r = m - 1;
else
l = m + 1;
}
return -1;
}

## main()

int main | ( | int | argc,
|  | char const * | argv[]
| ) |  |

main function

{
int n, key;
std::cout << "Enter size of array: ";
std::cin >> n;
std::cout << "Enter array elements: ";
int* a = new int[n];
// this loop use for store value in Array
for (int i = 0; i < n; i++) {
std::cin >> a[i];
}
std::cout << "Enter search key: ";
std::cin >> key;
// this is use for find value in given array
int res = binary_search(a, n - 1, key);
if (res != -1)
std::cout << key << " found at index " << res << std::endl;
else
std::cout << key << " not found" << std::endl;
delete[] a;
return 0;
}
std::cin
std::cout
binary_search
int binary_search(int a[], int r, int key)
Definition: binary_search.cpp:15
std::endl
T endl(T... args)
Here is the call graph for this function: