I've been reading some binary search algorithms I found on the internet, and I noticed this block of code within all examples I have encountered.
if (query > contents[midIndex])
{
minIndex = midIndex + 1;
}
else if (query < contents[midIndex])
{
maxIndex = midIndex - 1;
}
Why is that though? I tried doing this:
if (query > contents[midIndex])
{
minIndex = midIndex;
midIndex = (minIndex + maxIndex) / 2;
}
else if (query < contents[midIndex])
{
maxIndex = midIndex;
midIndex = (minIndex + maxIndex) / 2;
}
That code works in all the testing I've done, and isn't it faster? If it isn't faster, can someone explain the logic of the first snippet of code?