-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.java
executable file
·48 lines (40 loc) · 1.43 KB
/
BinarySearch.java
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
import java.io.* ;
public class BinarySearch {
public static void main (String args []) throws IOException {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in)) ;
int n ;
System.out.println ("Enter array size:") ;
n = Integer.parseInt (br.readLine()) ;
int range [] = new int [n] ;
int i;
for (i = 0 ; i < n ; i++) {
System.out.println ("Enter value for array in ascending order:") ;
int val = Integer.parseInt (br.readLine()) ;
range [i] = val ;
}
System.out.println ("Enter number for search:") ;
int element = Integer.parseInt (br.readLine ()) ;
int first = 0, last = n - 1, find = 0, mid = 0 ;
int pos = 0 ;
while (first <= last) {
mid = (first + last) / 2 ;
if (range [mid] == element) {
pos = mid ;
find = 1 ;
break;
}
if (element > range [mid] ) {
first = mid + 1 ;
}
else {
last = mid - 1 ;
}
}
if (find == 1) {
System.out.println ("Element found at " + (pos + 1) + " position") ;
}
else {
System.out.println ("Search not successful") ;
}
}
}