forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Search.java
35 lines (26 loc) · 853 Bytes
/
Binary_Search.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
import java.util.*;
class Main{
public static void main(String args[]){
int numArray[] = {5,10,15,20,25,30,35};
System.out.println("The input array: " + Arrays.toString(numArray));
int key = 20;
System.out.println("\nKey to be searched=" + key);
int first = 0;
int last=numArray.length-1;
int mid = (first + last)/2;
while( first <= last ){
if ( numArray[mid] < key ){
first = mid + 1;
}else if ( numArray[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
}