Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit acb024a

Browse files
Create Binary_search.java
1 parent 7729ceb commit acb024a

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎Binary_search.java‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import java.util.Scanner;
2+
public class Main
3+
{
4+
static int Binary_search(int a[],int n,int element)
5+
{
6+
int l=0,r=n-1;
7+
8+
while(l<=r)
9+
{
10+
int mid=(l+r)/2;
11+
if(element==a[mid])
12+
{
13+
return mid;
14+
}
15+
else if(element < a[mid])
16+
{
17+
r=mid-1;
18+
}
19+
else
20+
{
21+
l=mid+1;
22+
}
23+
}
24+
return -1;
25+
}
26+
public static void main(String[] args) {
27+
int n;
28+
System.out.print("Enter the size of array:");
29+
Scanner sc=new Scanner(System.in);
30+
n=sc.nextInt();
31+
int[] a=new int[n];
32+
for(int i=0;i<n;i++)
33+
{
34+
a[i]=sc.nextInt();
35+
}
36+
int element;
37+
System.out.print("Enter element:");
38+
element=sc.nextInt();
39+
int res=Binary_search(a,n,element);
40+
if(res==-1)
41+
{
42+
System.out.print("Element not found");
43+
}
44+
else
45+
{
46+
System.out.print("Element found at index"+res);
47+
}
48+
}
49+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /