简体   繁体   English

在二进制搜索和顺序搜索时比较计数比较麻烦,需要清楚

[英]having trouble comparison counting while in binary search and sequential, need clarity

I have a quick quick question but I am having trouble understanding, code sample below with commented documentation. 我有一个快速的问题,但是我在理解上有麻烦,下面的代码示例带有注释的文档。

When searching through an array of elements using binarySearch what is considering a comparison? 当使用binarySearch搜索元素数组时,正在考虑进行比较吗?

or in the case of int array containing 178,384,471,478,487,576,617,630,649,817,821,915,917,972,975 with 821 being the target what would the comparison count be??? 或如果int数组包含178,384,471,478,487,576,617,630,649,817,821,915,917,972,975821为目标),比较计数将是多少??

I have posted where I think comparisons take place, please correct me if I'm wrong, or tell me if I'm right please :) thanks all. 我已经张贴了我认为可以进行比较的地方,如果我错了,请纠正我,或者如果我错了,请告诉我:)谢谢。

public static int binarySearch(String[] data, String target, int first, int last)
{
  if(first > last)
     return -1;
  else
    int middle = (first+last)/2;
    int result = data[first].compareTo(data[middle])
    if(result == 0) //IS THIS A COMPARISON? (I THINK YES)
      return middle;
    else if(result < 0) // IS THIS A COMPARISON (I THINK YES)
      return binarySearch(data,target.first,middle-1);
    else
      return binarySearch(data,target,middle+1,last); // IS THIS A COMPARISON? (I THINK NO)
}

实际上,这是真实的比较int result = data[first].compareTo(data[middle]) if语句仅基于“真实”比较做不同的事情。

So, almost by definition, any equality or relational operator or method that wraps such an operator would be a comparison. 因此,几乎按照定义,任何等式或关系运算符或包装此类运算符的方法都是比较。

In general, what you probably want to assess is the order of your algorithms as the input grows, it is enough to count say times that the function gets called, even if inside there are 3 comparisons for instance. 通常,您可能要评估的是输入增加时算法的顺序,即使计算内部有3个比较,也足以计算调用该函数的次数。 The order (in this case O(log(n)) will not change. 顺序(在这种情况下,O(log(n))不会改变。

Side notes: you might want to use a actual array of integers instead of string comparison, which can be costly AND tricky (ie "12" > "110"). 旁注:您可能希望使用实际的整数数组而不是字符串比较,这可能会导致成本高昂且棘手(例如,“ 12”>“ 110”)。 Also, it would eliminate the need to get a "result", just do comparison against the stored values. 同样,这将消除获取“结果”的需要,只需与存储的值进行比较即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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