Skip to content

Commit 5029dbc

Browse files
author
Bhrigu Kansra
authored
Merge pull request #3 from aroraharsh010/master
Added binary search
2 parents 1aaf0db + 2fe9d9f commit 5029dbc

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

searching/BinarySearch.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
2+
import java.util.Scanner;
3+
4+
public class BinarySearch {
5+
6+
public static void main(String[] args)
7+
{
8+
Scanner scn=new Scanner(System.in);
9+
int N=scn.nextInt();
10+
int[] a=new int[N];
11+
boolean flag=false;
12+
for(int i=0;i<N;i++)
13+
{
14+
a[i]=scn.nextInt();
15+
}
16+
int low=0,high=(a.length)-1;
17+
int mid;
18+
19+
int n=scn.nextInt();
20+
while(high>=low)
21+
{
22+
mid=(high+low)/2;
23+
if (a[mid]>n)
24+
{
25+
high=mid-1;
26+
}
27+
else if (a[mid]<n)
28+
{
29+
low=mid+1;
30+
}
31+
else if (a[mid]==n)
32+
{System.out.println(mid);
33+
flag=true;
34+
break;}
35+
36+
}
37+
if (flag==false)
38+
{
39+
System.out.println(-1);
40+
}
41+
42+
}
43+
44+
}

0 commit comments

Comments
 (0)