Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
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

Function Documentation

◆ binary_search()

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

binary_search function

Parameters
[in]aarray to sort
[in]rright hand limit = \(n-1\)
[in]keyvalue to find
Returns
index if T is found
-1 if T is not found
15  {
16  int l = 0;
17 
18  while (l <= r) {
19  int m = l + (r - l) / 2;
20  if (key == a[m])
21  return m;
22  else if (key < a[m])
23  r = m - 1;
24  else
25  l = m + 1;
26  }
27  return -1;
28 }

◆ main()

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

main function

31  {
32  int n, key;
33  std::cout << "Enter size of array: ";
34  std::cin >> n;
35  std::cout << "Enter array elements: ";
36 
37  int* a = new int[n];
38 
39  // this loop use for store value in Array
40  for (int i = 0; i < n; i++) {
41  std::cin >> a[i];
42  }
43 
44  std::cout << "Enter search key: ";
45  std::cin >> key;
46 
47  // this is use for find value in given array
48  int res = binary_search(a, n - 1, key);
49  if (res != -1)
50  std::cout << key << " found at index " << res << std::endl;
51  else
52  std::cout << key << " not found" << std::endl;
53 
54  delete[] a;
55  return 0;
56 }
Here is the call graph for this function:
std::cout
binary_search
int binary_search(int a[], int r, int key)
Definition: binary_search.cpp:15
std::endl
T endl(T... args)
std::cin