为什么Big-O是O(N)而不是此代码的O(N/2)
我试图了解算法的大o。
我在网上找到了此代码,但我无法理解如何为其计算Big-O:
void printFirstItemThenFirstHalfThenSayHi100Times(int arr[], int size)
{
printf("First element of array = %d\n",arr[0]); % O(1)
for (int i = 0; i < size/2; i++) % O(n/2)
{
printf("%d\n", arr[i]);
}
for (int i = 0; i < 100; i++) % O(100), which is a constant
{
printf("Hi\n");
}
}
它说( big-o-with-示例),big-o是o(n)!为什么?
我看到我们在开始时有一个常数O(1),然后是O(N/2),最后是O(100)。为什么big-o是o(n)而不是o(n/2)?
I am trying to understand the Big-O of algorithms.
I found this code online and I wasn't able to understand how the Big-O was calculated for it:
void printFirstItemThenFirstHalfThenSayHi100Times(int arr[], int size)
{
printf("First element of array = %d\n",arr[0]); % O(1)
for (int i = 0; i < size/2; i++) % O(n/2)
{
printf("%d\n", arr[i]);
}
for (int i = 0; i < 100; i++) % O(100), which is a constant
{
printf("Hi\n");
}
}
It says (big-o-with-examples) that, the big-O is O(N)! why?
I see that we have a constant at the beginning O(1), then O(n/2), and finally O(100). Why the Big-O is O(N) and not O(N/2)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为
big-o(n)== big-o(1/2 * n)
,请放下常数因子。请参阅 (n/2)在大o符号中?
Because
Big-O(n) == Big-O(1/2 * n)
, drop the constant factor.See Is there such a thing as O(n/2) in Big O notation?