Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Big o 如何使用主定理计算大O_Big O - Fatal编程技术网

Big o 如何使用主定理计算大O

Big o 如何使用主定理计算大O,big-o,Big O,我一直在努力理解主定理有一段时间了。我找到的大部分信息似乎都假设我理解某些词汇。所以这里有一个很长的问题 考虑以下示例: const items = [1, 2, 3, 4, 5]; // O(1) Constant Time const getByIdx = idx => items[idx]; } // O(n) Linear Time const findItem = val => { for (let i = 0; i < items.length; i++)

我一直在努力理解主定理有一段时间了。我找到的大部分信息似乎都假设我理解某些词汇。所以这里有一个很长的问题

考虑以下示例:

const items = [1, 2, 3, 4, 5];

// O(1) Constant Time
const getByIdx = idx => items[idx];
}

// O(n) Linear Time
const findItem = val => {
  for (let i = 0; i < items.length; i++)
    if (items[i] === val) {
      return items[i];
    }
};

// O(n^2) Quadratic Time
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

const findItemInMatrix = val => {
  for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
      if (matrix[i][j] === val) {
        return matrix[i][j]
      }
    }
  }
};

// O(log n) Logarithmic Time
const arr = [1,2,3,4,5,6,7,8,9,10];

const binarySearch = (num, data) => {
  if (data.length === 1) {
    return data[0];
  }

  let low = data.splice(0, Math.ceil(data.length / 2));

  if (num > low[low.length - 1]) {
    return binarySearch(num, data);
  } else {
    return binarySearch(num, low);
  }
}
const items=[1,2,3,4,5];
//O(1)恒定时间
const getByIdx=idx=>items[idx];
}
//O(n)线性时间
const findItem=val=>{
for(设i=0;i{
for(设i=0;i{
如果(data.length==1){
返回数据[0];
}
设low=data.splice(0,Math.ceil(data.length/2));
如果(num>low[low.length-1]){
返回二进制搜索(num,data);
}否则{
返回二进制搜索(num,low);
}
}
上面的例子非常简单,可以不用公式来确定Big-O,但我很好奇如何使用公式来代替:

根据维基百科:

procedure p( input x of size n ):
   if n < some constant k:
     Solve x directly without recursion
   else:
     Create a subproblems of x, each having size n/b
     Call procedure p recursively on each subproblem
     Combine the results from the subproblems
程序p(输入尺寸为n的x):
如果n<某个常数k:
无需递归直接求解x
其他:
创建一个x的子问题,每个子问题的大小为n/b
对每个子问题递归调用过程p
合并子问题的结果
这里是我迷路的地方:

什么是子问题?在我的代码中,哪些行是子问题?
“子问题”对我来说很模糊。子问题是……
一份声明<代码>退货项目[i]
表情<代码>退货项目[i]+1
一圈

我应该为a和b插入什么值?

k来自哪里?


如何在这些示例中使用公式?

主定理用于计算递归函数的渐近复杂性。因此,代码中唯一的“子问题”是对自身进行的递归调用
binarySearch
。对于其他算法,您不应该使用主定理来计算复杂性


a
b
分别表示递归调用的数量和传递给每个调用的输入集的“收缩因子”。
k
的值无关紧要,如果条件只是解释递归最终终止(在您的情况下,当长度为1时)。

谢谢。你能澄清一下“
a
b
表示递归调用的数量…”吗?因此,在上面的10项数组示例中,它是否会转化为
T(10)=5T(10/2)+f(10)
?@dapperdan1985在处理渐近行为时使用有限小测试输入可能会产生误导。@dapperdan1985基本上是的。