Why does binary search work this way?

Click For Summary
Binary search operates by repeatedly dividing the search range in half, which is achieved through adjusting the beginning and end indices. The adjustments of end = middle - 1 and beginning = middle + 1 are crucial to avoid re-evaluating the middle element in subsequent iterations. Without these adjustments, the algorithm could enter an infinite loop or miss values, particularly due to integer division rounding. The discussion emphasizes that each iteration either finds the searched value or narrows the search range, ensuring efficiency. Understanding these adjustments is key to grasping why binary search is effective.
Arnoldjavs3
Messages
191
Reaction score
3

Homework Statement


Java:
public class BinarySearch {
    public static boolean search(int[] array, int searchedValue) {
        int beginning = 0;
        int end = array.length - 1;

        while (beginning <= end) {
            int middle = (beginning + end) / 2;
            if (array[middle] == searchedValue) {
                return true;
            }
            else if (array[middle] > searchedValue) {
                end = middle - 1;
            }
            else if (array[middle] < searchedValue) {
                beginning = middle + 1;
            }
          
        }
        return false;
    }
}
/*
middle = 3
array[3] > -3
end = 3;
middle = 0 + 3 /2 = 1.5 so 1
array[1]>-3
end = 1
middle = 0 + 1 /2 = 0
array[0] == -3
return true
*/

Homework Equations

The Attempt at a Solution


The following code is meant to search if an array has a searched value(from the user). My question is why do we need to do this:
end = middle - 1
and
beginning = middle + 1

I noticed that when I input some values without the + and - 1 in the algorithm that it still works, to a varying degree. Why is this?
 
Physics news on Phys.org
Arnoldjavs3 said:
I noticed that when I input some values without the + and - 1 in the algorithm that it still works, to a varying degree. Why is this?
Think about what one iteration through the loop will accomplish. Written down in words:

Each iteration will either: 1) Find the searched-for value or 2) Reduce the remaining range to be searched.

Can you think of a way that 2) could fail without the -1 and +1? Hint: integer division.
 

Similar threads

  • · Replies 18 ·
Replies
18
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 17 ·
Replies
17
Views
6K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
2
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K