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?
Well, all I can say is that, the first part is NOT binary search at all. (+ it doesn’t even seem to recalculate the
midIndexvariable)The purpose of binary searches is to be “focusing” the searches in “halves” of the total range until the spectrum has been narrowed down to the element we’ve been looking for…