In each of the five questions below, you are given a program fragment. Estimate
ID: 3873888 • Letter: I
Question
In each of the five questions below, you are given a program fragment. Estimate the running time for each program fragment in terms of n. Assume that the value of n is determined elsewhere in the program. You should make your upper bound and lower bound as tight as you can. For each question:
1. State an upper bound on the running time of the program fragment using O( ) notation.
2. Briefly justify your upper bound.
3. State a lower bound on the running time of the program fragment using ( ) notation.
4. Briefly justify your lower bound.
Even in cases where the upper bound and lower bound are the same function, the justifications would be different. (For upper bounds, you are claiming that the code will run no slower than the upper bound. For lower bounds, you are claiming that the code will take at least that amount of time.) Remember that flex days do not apply to homework assignments. Type Omega() for () and n^2 for n2.
A) the program fragment resides in the main() function. The program fragment calls a function checkthis(). In your running time estimates, include the time to execute the program fragment in main() and the time to execute the function calls.
void checkthis(int top) { // function definition outside main() while (top > 1) { top = top / 2 ; } } // ... in the main() function ... for (int i=0 ; i < n ; i++) { checkthis(i) ; }
B) this question, the program fragment resides in the main() function. The program fragment calls a function loop(). In your running time estimates, include the time to execute the program fragment in main() and the time to execute the function calls
// function definition outside main()
int checker(int x) { int something = 0 ; for (int i=0 ; i < x ; i++) { something++ ; } return something ; }
// ... in the main() function ... int sum = n ; sum = sum + checker(3) ; sum = sum + checker(5) ;
C)
for (int i=0 ; i < n ; i++) { int j = 2*i ; while (j < n) { j = j + 2 ; } }
D)
t = 1 ; for (int i=0 ; i< n ; i++) { t = t++ ; } while ( t > 1 ) { t = t / 2 ; }
E)
int sum = 0 ; int i = 1 ; while (sum <= n) { sum = sum + i ; i++ ; }
Explanation / Answer
for (int i=0 ; i < n ; i++) {
checkthis(i) ;
}
void checkthis(int top) {
// function definition outside main()
while (top > 1) {
top = top / 2 ;
}
}
---------------------------
Worst Case - where n = 0 ; -> O(1)
0
1
1+1 = 2 = O(N)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.