Skip to content

Commit 5ba4dc3

Browse files
Merge pull request #57 from ragupathi09/master
C++ Binary search
2 parents 59d99e1 + 215ee8b commit 5ba4dc3

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

C++/Binary_search.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include<iostream>
2+
using namespace std;
3+
// recursive function for binary search
4+
/* if match found then return index of search key
5+
else return -1 */
6+
int binarySearch(int arr[], int low, int high, int key) {
7+
if (high >= low) {
8+
// find middle index
9+
int mid = low + (high - low) / 2;
10+
11+
// find middle term and compare
12+
if (arr[mid] == key) return mid; // key found
13+
14+
// If key is smaller than middle term, then
15+
// it can only be present in left subarray
16+
if (arr[mid] > key)
17+
return binarySearch(arr, low, mid - 1, key);
18+
19+
// Else the key can only be present
20+
// in right subarray
21+
return binarySearch(arr, mid + 1, high, key);
22+
}
23+
24+
// key not found
25+
return -1;
26+
}
27+
28+
// main function
29+
int main()
30+
{
31+
int array[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
32+
int key = 0;
33+
34+
// take input for the search key
35+
cout << "Enter Search Element: ";
36+
cin >> key;
37+
38+
// find the size array
39+
int size = sizeof(array)/sizeof(array[0]);
40+
41+
// search key
42+
int index = binarySearch(array, 0, size, key);
43+
44+
// display result
45+
if(index == -1)
46+
cout << key << " Not Found" << endl;
47+
else
48+
cout << key << " Found at Index = " << index << endl;
49+
50+
return 0;
51+
}

0 commit comments

Comments
 (0)