-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathBinary_Searching.java
More file actions
52 lines (51 loc) · 830 Bytes
/
Binary_Searching.java
File metadata and controls
52 lines (51 loc) · 830 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
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <stdio.h>
#include <array>
using namespace std;
int binarySearch(int arr[], int len, int key)
{
int prev=0;
int post = len-1;
int mid=0;
while(prev<=post)
{
mid=(prev+post)/2;
if(arr[mid]==key)
{
return mid;
}
else if(arr[mid]>key)
{
post=mid-1;
}
else
{
prev=mid+1;
}
}
return -1;
}
int main()
{
int n;
cout<<"give number"<<endl;
cin>>n;
int a[n];
cout<<"give array"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int k;
cout<<"give the number to search"<<endl;
cin>>k;
int x=binarySearch(a,n,k);
if(x==-1)
{
cout<<"Not Found";
}
else
{
cout<<"Found at "<<x;
}
}