-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.java
More file actions
46 lines (46 loc) · 960 Bytes
/
binarysearch.java
File metadata and controls
46 lines (46 loc) · 960 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
//Binary Search
import java.util.Scanner;
class binarysearch
{
public static void main(String[] args)
{
System.out.println("Enter the size of the array");
int size=new Scanner(System.in).nextInt();
int a[]=new int [size];
System.out.println("Enter array elements");
for(int i=0;i<size;i++)
{
a[i]=new Scanner(System.in).nextInt();
}
System.out.println("Enter the element you want to search");
int search=new Scanner(System.in).nextInt();
if(search<a[0] || search>a[size-1])
{
System.out.println("Number not found");
System.exit(0);
}
int start=0;
int stop=size-1;
while(start<=stop)
{
int mid=(start+stop)/2;
if(search==a[mid])
{
System.out.println("Number found");
break;
}
if(search<a[mid])
{
stop=mid-1;
}
if(search>a[mid])
{
start=mid+1;
}
}
if(start>stop)
{
System.out.println("Number not found");
}
}
}