Skip to content

Commit 65c2716

Browse files
authored
Merge pull request #20 from goyaldhara/master
Added binary_search in separate folder
2 parents 271ed56 + 6e0a0e5 commit 65c2716

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Searching/Binary_Search_array.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//Searching algorithm for a key in an array
2+
//Searching Algorithm: Binary Search
3+
//Time Complexity: In searching O(log(n)) Sorting O(nlog(n)) Overall: O(nlog(n))
4+
//Language Used: C++
5+
//Author: goyaldhara
6+
#include<bits/stdc++.h>
7+
using namespace std;
8+
int Binary_Search(int arr[],int start,int end,int key)
9+
{
10+
// This function will return 1 if the key is found in the array, else it will return 0;
11+
while(start<=end)
12+
{
13+
int mid=(start)+(end-start)/2;
14+
if(arr[mid] == key)
15+
return 1;
16+
if(arr[mid] < key)
17+
start = mid+1;
18+
else
19+
end=mid-1;
20+
}
21+
return 0;
22+
}
23+
int main()
24+
{
25+
int n,key; //size of array in which the key is to be searched
26+
cin>>n;
27+
int arr[n+10];
28+
for(int i=0;i<n;i++)
29+
cin>>arr[i];
30+
cin>>key;
31+
sort(arr,arr+n);
32+
cout<<Binary_Search(arr,0,n-1,key)<<'\n';
33+
34+
return 0;
35+
}

0 commit comments

Comments
 (0)