No_name
No_name

Reputation: 2810

Binary Search Algorithm Confusion

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?

Upvotes: 0

Views: 265

Answers (2)

Neil Luo
Neil Luo

Reputation: 1

 You can achieve binary search by loop or recursion and there are so many code 

in the Internet.The principle of the binary search is like search one page in a book.The pages is orderd and you will look for one half every time.This is the principle of your first snippet of code.

 About the speed of the two segments,I think they are not whole.Binary search is 

not so easy and there are some details should be noticed.Please google for it!

Upvotes: 0

Dr.Kameleon
Dr.Kameleon

Reputation: 22810

Well, all I can say is that, the first part is NOT binary search at all. (+ it doesn't even seem to recalculate the midIndex variable)

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...

Upvotes: 1

Related Questions