Java – how many calculations must a computer perform in a binary search?
Here, I have an array:
{1,3,5,6,7,8,9,11,13,14,15}
It's simple. However, we will use binary search to search the index of integer 3 How many comparisons does the computer need to make?
Look, I think these are three comparisons, but somehow this is not correct Someone will explain how many comparisons the computer needs to make and why? I'm new to programming, and I don't understand the concept well
Solution
The binary search algorithm on this sequence will be as follows So, we're looking for 3. We compare the element in the middle of the sequence with 3
{1,15} =? 3
They are not equal, so using the left subsequence, we compare 3 with its intermediate element, i.e
{1,7} =? 3
They are still not equal, and then we go to the left subsequence, 3}
We compare with the middle elements, but we have a list of size 2! If we choose as the intermediate element 1, we need to make another comparison, that is, we need to recurse to the correct subsequence, that is {3} In that case, we will make 4 comparisons!
But wait, there's another trick. You also need to check the basic situation at each iteration or recursive call and use these accounts for other comparisons!