Skip to content

Commit 7c7caa3

Browse files
committed
Binary Search Added to Java
1 parent 7e5d56f commit 7c7caa3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.util.Scanner;
2+
public class Main {
3+
private static int binarySearch(int arr[], int x) {
4+
int l = 0, r = arr.length - 1;
5+
while (l <= r) {
6+
int m = l + (r - l) / 2;
7+
// Check if x is present at mid
8+
if (arr[m] == x)
9+
return m;
10+
// If x greater, ignore left half
11+
if (arr[m] < x)
12+
l = m + 1;
13+
// If x is smaller, ignore right half
14+
else
15+
r = m - 1;
16+
}
17+
// if we reach here, then element was
18+
// not present
19+
return -1;
20+
}
21+
public static void main(String[] args) {
22+
Scanner scan = new Scanner(System.in);
23+
try {
24+
int i,n,x, last;
25+
System.out.println("How many elements do you want in the array?");
26+
n=scan.nextInt();
27+
int a[]= new int[n];
28+
System.out.println("Enter the array elements one by one");
29+
for(i=0;i<n;i++)
30+
{
31+
a[i]=scan.nextInt();
32+
}
33+
System.out.println("Enter Element to found");
34+
x = scan.nextInt();
35+
last = a.length -1 ;
36+
int result = binarySearch(a, x);
37+
if (result == -1)
38+
System.out.println("Element not present");
39+
else
40+
System.out.println("Element found at "
41+
+ "index " + result);
42+
} catch(Exception e) {e.printStackTrace();}
43+
scan.close();
44+
}
45+
}

0 commit comments

Comments
 (0)