-
Notifications
You must be signed in to change notification settings - Fork 5
/
BinarySearch.java
35 lines (35 loc) · 1.23 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
import java.util.*;
class BinarySearch{
public static void main(String args[]){
int numArray[] = {5,10,15,20,25,30,35};
System.out.println("The input array: " + Arrays.toString(numArray));
//key to be searched
int key = 20;
System.out.println("\nKey to be searched=" + key);
//set first to first index
int first = 0;
//set last to last elements in array
int last=numArray.length-1;
//calculate mid of the array
int mid = (first + last)/2;
//while first and last do not overlap
while( first <= last ){
//if the mid < key, then key to be searched is in the first half of array
if ( numArray[mid] < key ){
first = mid + 1;
}else if ( numArray[mid] == key ){
//if key = element at mid, then print the location
System.out.println("Element is found at index: " + mid);
break;
}else{
//the key is to be searched in the second half of the array
last = mid - 1;
}
mid = (first + last)/2;
}
//if first and last overlap, then key is not present in the array
if ( first > last ){
System.out.println("Element is not found!");
}
}
}