[英]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#): 下面是示例代码(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). 我可以看到,要查找从2047到4096范围内的随机数,最多需要进行11次操作(基于10000次运行)。
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. 因此,如果我有200个数字,则第一次迭代会将其降低到100,第二次迭代将其降低到50,然后是25、12、6、3、1,我们就完成了。 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. 特别是,由于我们要处理二进制搜索,因此它的底数为指数2。
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. 所以,如果你想知道你能有多少价值与操作的给定数量的搜索,它只是两个力量-如果你只想让8次操作,最多可以有2 ^ 8个值中搜索- 256。如果要从值的数量到(最大)操作数相反,则需要使用反函数-以2为底的对数。 The base-two logarithm of 4096 is 12. 4096的以2为底的对数是12。
Why is your result 11? 为什么您的结果为11? Because you don't increment the counter when i == val
is true; 因为当i == val
为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. 涉及11个减半,因为最终操作不会减半。
4096 - 2047 = 2049, which equals 2^11 + 1 4096-2047 = 2049,等于2 ^ 11 +1
Your answer is the power of 2, which gives you the size of the interval within which you search. 您的答案是2的幂,它给出了搜索间隔的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.