-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbinary_search.java
More file actions
47 lines (39 loc) · 923 Bytes
/
binary_search.java
File metadata and controls
47 lines (39 loc) · 923 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
47
package program2;
import java.io.*;
import java.util.Scanner;
public class program2 {
public static void main(String[] args) {
int []my_array = new int[1000];
int size,lower,upper,mid;
System.out.println("Enter the array size");
Scanner in = new Scanner(System.in);
size = in.nextInt();
lower = 0;
upper = size-1;
mid = lower + (lower+upper)/2;
System.out.println("Enter the array elements");
for(int i=0;i<size;i++)
{
my_array[i] = in.nextInt();
}
System.out.println("Enter the search element");
int element = in.nextInt();
for(int i=0;i<size;i++)
{
if(my_array[mid]<element)
{
lower = mid + 1;
mid = lower+(lower+upper)/2;
}
if(my_array[mid]>element)
{
upper = mid - 1;
mid = lower + (lower+upper)/2;
}
}
if(my_array[mid]==element)
{
System.out.println("We found it");
}
}
}