Question

What indexes will be examined as the middle element by a binary search for the target...

What indexes will be examined as the middle element by a binary search for the target value 8 when the search is run on the following input array? Check if the input array is in sorted order. What can you say about the binary search algorithm’s result?

int[] numbers = {6, 5, 8, 19, 7, 35, 22, 11, 9};

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

(Using Java code please)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

int[] numbers = {6, 5, 8, 19, 7, 35, 22, 11, 9}; for this array it will not work as it is not in the sorted order

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

here first we will check with as 5 as it is middle element

next as 8>5 we will move right and check with 7

so next 8>7 we will move to right and check with 8

so 8==8 we will return true

public class BinarySearchIterative {
   public static void main(String[] args) {
       int[] numbers1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
       int[] numbers2= {6, 5, 8, 19, 7, 35, 22, 11, 9};
       System.out.println(binarySearch(numbers1, 8));
       System.out.println(binarySearch(numbers2, 8));
   }
   public static int binarySearch(int sortedArray[], int x)
{
       if(!isItSorted(sortedArray))
           return -1;
int l = 0, r = sortedArray.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
System.out.println(sortedArray[m]);
if (sortedArray[m] == x)
return m;
  
// If x greater, ignore left sub array
if (sortedArray[m] < x)
l = m + 1;
  
// If x is smaller, ignore right sub array
else
r = m - 1;
}
return -1;
}
   private static boolean isItSorted(int[] arr) {
       for(int i=0;i<arr.length-1;i++) {
           if(!(arr[i]<arr[i+1]))
               return false;
       }
       return true;
   }
}

Add a comment
Know the answer?
Add Answer to:
What indexes will be examined as the middle element by a binary search for the target...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT