Answer to Question #290491 in Java | JSP | JSF for Debby

Question #290491

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.


1
Expert's answer
2022-01-25T10:46:54-0500
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));
    }
}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS