表达为大O符号

时间:2014-09-28 01:41:23

标签: c performance algorithm big-o

所以我明白,如果两个while循环只是while(x

    int result = 0;
    int x = 0;
    while (x < n / 2){
            result += arr[x];
            x += 1;
            while (x >= n / 2 && x < n){
                    result += arr[x];
                    x += 1;
            }
     }
     printf("%d\n", result);

1 个答案:

答案 0 :(得分:0)

程序片段实际上是对数组元素的总和。 如果n是元素的数量,那么它运行第一个循环n / 2次和内部(第二个)循环n / 2次,总共n次,因此,它是O(n)。 让我们一步一步地解释一下: 说,

int arr[] = {10, 20, 30, 40, 50}; 
int n = 5;

这些是执行步骤:

1. (first loop) arr[0](10) is added, result becomes 10, x becomes 1
2. (first loop) arr[1](20) is added, result becomes 30, x becomes 2
3. (first loop) arr[2](30) is added, result becomes 60, x becomes 3
4. (first loop) arr[3](40) is added, result becomes 100, x becomes 4
5. (first loop) arr[4](50) is added, result becomes 150, x becomes 5

因此,第一个循环执行楼层(n / 2)次,即2次(步骤1,2) 而在步骤2中,它运行第二内环(x> = n / 2,即x> = 2),并且第二循环运行上限(n / 2),即3次(步骤3,4,5),并且两者都运行循环结束 因此,总时间复杂度为O(n)。 但是,这可以做得更简单:

 int result = 0;
 int x = 0;
 while (x < n){
  result += arr[x];
  x += 1;
 }
 printf("%d\n", result);