The world’s Largest Sharp Brain Virtual Experts Marketplace Just a click Away
Levels Tought:
Elementary,Middle School,High School,College,University,PHD
| Teaching Since: | Jul 2017 |
| Last Sign in: | 314 Weeks Ago |
| Questions Answered: | 15833 |
| Tutorials Posted: | 15827 |
MBA,PHD, Juris Doctor
Strayer,Devery,Harvard University
Mar-1995 - Mar-2002
Manager Planning
WalMart
Mar-2001 - Feb-2009
I'm using C language*
Question 1 – Determine Running Time: 8 marks
For each of the following code fragments determine the worst-case O notation running time and briefly justify your answer. In each case your answer should be a function of n. If the question refers to an array you can assume that the size of that array is n. Note that you are not expected to derive a detailed cost function, just the Big O notation running time.
Â
Example
for (i = 1; i <= n; i++) { Â
    sum = sum + i;
}
Â
Answer: The loop body runs in O(1) and the loop is executed O(n) times. Total running time is O(1)×O(n)=O(n).
Â
a
for (int i = 0; i < n; i++) {
      for (int j = 0; j < 3; j++) {
         for (int k = 0; k < 3; k++) {
            printf("%d", arr[i]);
           }
         printf("n");
      }
}
Â
b
for (int i = 2; i <= n; i++) {
      int j;
      printf("n%d:", i);
      for(j = 2; j <= i; j = j * 2){
         printf("%d ", j);
      }
      printf("n%d:", i);
      for(int k = j/2; k >= 2; k = k / 2){
         printf("%d ", k);
      }
}
Â
c
int i = 0;
int j = 0;
while(i < n){
      while(j < n){
         printf("{%d,%d}",arr[i],arr[j]);
         j++;
      }
      i++;
      j = 0;
      printf("n");
}
Â
d
int result = 0;
int i = 0;
while (i < n / 2){
      result += arr[i];
      i += 1;
      while (i >= n / 2 && i < n){
         result += arr[i];
         i += 1;
      }
}
printf("%dn", result);
----------- Â ----------- H-----------ell-----------o S-----------ir/-----------Mad-----------am ----------- Th-----------ank----------- yo-----------u f-----------or -----------you-----------r i-----------nte-----------res-----------t a-----------nd -----------buy-----------ing----------- my----------- po-----------ste-----------d s-----------olu-----------tio-----------n. -----------Ple-----------ase----------- pi-----------ng -----------me -----------on -----------cha-----------t I----------- am----------- on-----------lin-----------e o-----------r i-----------nbo-----------x m-----------e a----------- me-----------ssa-----------ge -----------I w-----------ill----------- be----------- qu-----------ick-----------ly