57.4k views
18 votes
In a binary search, which formula is used to find the index of the middle value?

middle = (first + last) * 2


middle = (first + last) // 2


middle = first + last // 2


middle = first + last * 2

User RageCage
by
4.8k points

1 Answer

13 votes

Answer:

middle = (first + last) // 2

Step-by-step explanation:

In binary search algorithm, the searching begins at the middle index and if the value searched for is not the middle element, it progresses to the left or right of the element depending on the size of the value compared to the middle element.

To determine the middle index, you add the first index to the last index and divide the result by 2. By doing this you eliminate half of the elements you have to search through.

Subsequent divisions eventually gets you to the element you're searching for in lesser time compared to if you had to search through every element in the array.

User Spbfox
by
5.8k points