Consider the following list of numbers:
1 7 8 14 20 42 55 67 78 101 112 122 170 179 190
Apple binary search algorithms in order to find the target keys which are number 42 and number 82. Show your steps and calculate the total number of comparisons for each items.
public class Main {
public static int binarySearch(int[] array, int key) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int middle = (left + right) / 2;
if (array[middle] > key) {
right = middle - 1;
} else if (array[middle] < key) {
left = middle + 1;
} else {
return middle;
}
}
return -1;
}
public static void main(String[] args) {
int[] array = {1, 7, 8, 14, 20, 42, 55, 67, 78, 101, 112, 122, 170, 179, 190};
System.out.println(binarySearch(array, 42));
System.out.println();
System.out.println(binarySearch(array, 82));
}
}
Comments
Leave a comment