File size: 843 Bytes
c574d3a |
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 |
public class BinarySearch {
public static void main(String[] args) {
int[] arr = { 3, 6, 9, 12, 15 };
int key = 15;
int arrlength = arr.length;
binarySearch(arr, 0, key, arrlength);
}
public static void binarySearch(int[] arr, int start, int key, int length) {
int midValue = (start + length) / 2;
while (start <= length) {
if (arr[midValue] < key) {
start = midValue + 1;
} else if (arr[midValue] == key) {
System.out.println("Element is found at index: " + midValue);
break;
} else {
length = midValue - 1;
}
midValue = (start + length) / 2;
}
if (start > length) {
System.out.println("Element is not found");
}
}
}
|