-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathBinary_Search.java
More file actions
66 lines (49 loc) · 1.14 KB
/
Binary_Search.java
File metadata and controls
66 lines (49 loc) · 1.14 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//Aditya Mali
//22-10-2022
//Binary Search using Java
import java.util.*;
public class Binary_Search
{
public static void main(String args[])
{
int i , n , s , k=0;
int a[];
int low , mid , high ;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements: ");
n = sc.nextInt();
a = new int[n];
System.out.println("Enter " + n + " integers in Ascending Order: ");
for (i = 0; i < n; i++)
{
a[i] = sc.nextInt();
}
System.out.println("Enter the no. you want to search :");
s = sc.nextInt();
low = 0;
high = n - 1;
mid = (low + high)/2;
while(low <= high)
{
if (a[mid] < s)
{
low = mid + 1;
}
else if (a[mid] == s)
{
System.out.println(s + " found at position " + (mid + 1));
k=1;
break;
}
else
{
high = mid - 1;
}
mid = (low + high)/2;
}
if(k==0)
{
System.out.println("Number not found in Array");
}
}
}