-2
#define MAX 20    //defines max as 20  
#include< stdio.h>  

main()    //main function starts  
{  
    int a[MAX],i,n;  //defines a array along with some variables  `

    printf("Enter the value of n\n");    //take the size of the array from user  
    scanf("%d",&n);    //reads the value
    printf("Enter the numbers\n");    //asks to enter the values of array  
    for(i=0;i< n;i++)    //for loop is used to read the elements of the array     
    scanf("%d",&a[i]);    //reads the element    

    i=0;    //initialises i to zero to point it to the first element of array  
    do    //starts the do while loop      
    {  
        a[i]=a[i]+1;    //increases the stored value of the array by 1  
        i++;  
    } while(i< n);    //checks the while condition whether i is less than n  

    printf("The final array is \n");  
    for(i=0;i< n;i++)    //for loop is used to print the array  
        printf("%d\t",a[i]);    //prints the final array  
}  

如果 i 的值在 do while 循环内发生变化,并且如果它发生变化,那么效率会发生变化,那么它是如何变化的。

如果将while循环更改如下,效率会是多少

int j=0;
do{
  if(j==n-2 || j==n-3)
    i--;
  else 
  {
    a[i]=a[i]++;
    i++;
    j++;
  }
} while(i< n);
4

3 回答 3

1

答案是 O(3n) = O(n) 因为你的循环从 0 增加到 (n-1) 3 次。

于 2012-11-08T17:04:26.913 回答
0

上)

我认为这就是你试图以一种有组织的“智能”方式编写的内容:

#include< stdio.h>  
main()
{  
    int *a;
    int i;
    int n;

    printf("Enter the value of n\n");
    scanf("%d",&n);
    a = (int*)malloc(n * sizeof(*a));//dynamically allocate the array in the needed size.
    printf("Enter the numbers\n");
    for(i=0; i<n; ++i)
    {
        scanf("%d",&a[i]);
    }

    for(i=0; i<n; ++i)
    {
        a[i]++;
    }

    for(i=0; i<n; ++i)
    {
        printf("%d\t",a[i]);
    }
} 
于 2012-11-08T17:22:16.720 回答
0

该算法是 O(∞),因为i在中间循环中从不递增。

于 2012-11-08T16:59:30.450 回答