简体   繁体   中英

Find number with binary search - maximum and minimum number of operations

I want to know how can I calculate the maximum and minimum number of operations to find the specific number in defined range.
Here the example code (C#):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Random r = new Random();
            int min = 2047;
            int max = 4096;
            int val = min;
            int counter = 0;                
            int i = r.Next(2047, 4096);                
            while(true)
            {
               Console.WriteLine("--> "+val);
               if(i == val) break;                    
               val = (max-min)/2 + min;                    
               if(i>val) {
                   min = val;
               }
               else if(i<val) {
                   max = val;
               }
               counter++;
            }
            Console.WriteLine("\n\nThe calculated i is: "+val+", but i is: "+i+", done in "+counter+" counts.\n\n\n\n\n");
        }
    }
}

I can see that to find the random number in range from 2047 to 4096 takes 11 operations maximum (based on 10000 runs).
Where can I find a theoretical explanation of the calculation?

Thanks a lot!

The way binary search works is that you halve the search interval on each operation. So if I have 200 numbers, the first iteration will get it down to 100, the second to 50, then 25, 12, 6, 3, 1 and we're done. If you have some mathematical background, this pattern looks very familiar - it's an exponential function. In particular, since we're dealing with binary search, it's an exponential with base two.

So if you want to know how many values you can search with a given number of operations, it's just that power of two - if you only want to allow 8 operations, you can have up to 2^8 values to search in - 256. If you want to go the other way around, from number of values to (maximum) number of operations, you need to use the inverse function - a logarithm with base two. The base-two logarithm of 4096 is 12.

Why is your result 11? Because you don't increment the counter when i == val is true; but that's only a matter of definition of operation that you use. There's 11 halvings involved, since the final operation doesn't do any halving.

4096 - 2047 = 2049, which equals 2^11 + 1

Your answer is the power of 2, which gives you the size of the interval within which you search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM