Skip to content

Commit f96f136

Browse files
authored
Merge pull request #429 from siddhi-244/Siddhi/Binary-search
Added binary search in cpp.
2 parents b60b366 + fc7772d commit f96f136

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*Program for Binary Search */
2+
/*Binary search is another searching algorithm which is more effective than the linear Search. Searching algorithms are used to search a desired element in an array.Binary Search does less number of comparisons than linear Search,so it is an effective algorithm.Binary Search works only on sorted array. It follows divide and conquer approach.*/
3+
4+
/*algorithm
5+
The array should be sorted.
6+
We take 3 variables start,mid and end. Start variables has the index of 0th element end variable has index of last element and mid points to middle element.
7+
We run a loop until start<=end.
8+
We check if our desired element is equal to mid element.
9+
If yes then return mid.
10+
If desired element is greater than the mid element then we search in the right array.
11+
If desired element is less than the mid element then we search in the left array.
12+
Else return -1.*/
13+
#include <iostream>
14+
using namespace std;
15+
int binary_search(int a[],int n,int key){
16+
int s=0;
17+
int e=n-1;
18+
//start should not cross end
19+
20+
while(s<=e){
21+
int mid=(s+e)/2;
22+
if(a[mid]==key){
23+
return mid;
24+
}
25+
// search in left of Array
26+
else if(a[mid]>key){
27+
e=mid-1;
28+
29+
}
30+
//search in right of Array
31+
else{
32+
s=mid+1;
33+
}
34+
35+
36+
}
37+
return -1;
38+
}
39+
int main() {
40+
int n;
41+
cout<<"Size of Array "<<endl;
42+
cin>>n;
43+
int a[1000];
44+
cout<<"Enter Array Elements: "<<endl;
45+
for(int i=0;i<n;i++){
46+
cin>>a[i];
47+
}
48+
int key;
49+
cin>>key;
50+
cout<<binary_search(a,n,key);
51+
52+
}
53+
/*Examples
54+
For example let the array be [4,5,8,9,11]
55+
We have to search 9 in the array.
56+
Here, start =0,end=4 and mid=(start+end)/2,mid=2
57+
a[mid]=8 which is not equal to 9
58+
a[mid]<9 hence, start=mid+1
59+
start=3,end=4,mid=(3+4)/2=3
60+
a[mid]=9 which is equal to 9 so we return 3.
61+
*/

0 commit comments

Comments
 (0)