为什么Big-O是O(N)而不是此代码的O(N/2)

发布于 2025-01-28 05:14:44 字数 704 浏览 1 评论 0原文

我试图了解算法的大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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

楠木可依 2025-02-04 05:14:44

因为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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文