-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBsearch.java
More file actions
41 lines (41 loc) · 795 Bytes
/
Copy pathBsearch.java
File metadata and controls
41 lines (41 loc) · 795 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
import java.util.Scanner;
public class Bsearch
{
public static void main(String[] args)
{
int size=10, i, search, first, last, middle;
int[] arr = new int[size];
Scanner scan = new Scanner(System.in);
System.out.print("Enter 10 Elements (in Ascending): ");
for(i=0; i<size; i++)
{
arr[i] = scan.nextInt();
}
System.out.print("Enter an Element to Search: ");
search = scan.nextInt();
first = 0;
last = size-1;
middle = (first+last)/2;
while(first<=last)
{
if(arr[middle]<search)
{
first = middle+1;
}
else if(arr[middle]==search)
{
System.out.println("\nThe element is available at Index No." +middle);
break;
}
else
{
last = middle-1;
}
middle = (first+last)/2;
}
if(first>last)
{
System.out.println("\nThe element is not available in given array");
}
}
}