Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

number of comparisons of binary search

What is the total number of comparisons necessary to locate all the n sorted distinct integers in an array using binary search? I think the number is n log2 n (2 is the base), but I am not sure. What do you think?

like image 436
alan Avatar asked Apr 19 '26 19:04

alan


1 Answers

If you want an exact answer, then it is clearly not N log(N) or N log2(N). For most integers N, logN and log2 are not rational, but the number of comparisons must be an integer value.

Also, the exact answer will depend on implementation details of the binary search algorithm. For example, if a "comparison" is a simple relation that returns true and false, more comparisons are required than when a "comparison" returns negative, zero or positive. (In the latter case, you can short circuit when the algorithm hits the key early.)

like image 198
Stephen C Avatar answered Apr 21 '26 07:04

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!