-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
41 lines (40 loc) · 771 Bytes
/
Copy pathbinarysearch.cpp
File metadata and controls
41 lines (40 loc) · 771 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream>
using namespace std;
int binarysearch(int arr[],int n,int key)
{
int start=0;
int end=n-1;
int mid=start+(end-start)/2;
while(start<=end)
{
if(arr[mid]==key)
{
return mid;
}
else if(key>arr[mid])
{
return start=mid+1;
}
else if(key<arr[mid])
{
return end=mid-1;
}
mid=start+(end-start)/2;
}
return -1;
}
int main()
{
int n, key;
cout<<"enter size of array and key element to search";
cin>>n>>key;
int arr[n];
cout<<"enter array elements";
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int index=binarysearch(arr,n,key);
cout<<index;
}
//time complexity=O(LOGN)