Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: THEend8_
CS526 O2 Homework Assignment 2 Problem 1 (20 points).
This problem is a practice of analyzing running time of algorithms.
Express the running time of the following methods,
which are written in a pseudocode style, using the big-oh notation.
Assume that all variables are appropriately declared.
You must justify your answers. If you show only answers, you will not get any credit even though they are correct.
(1) method1(int[ ] a) // returns integer x = 0; y = 0; for (i=1; i
if (a[i] == a[i‐1]) {
x = x + 1;
}
else {
y = y + 1;
}
}
return (x ‐ y);
(2)
method2(int[ ] a, int[ ] b) // assume equal‐length arrays
x = 0;
i = 0;
while (i < n) { // n is the number of elements in each array
y = 0;
j = 0;
while (j < n) {
k = 0
while (k <= j) {
y = y + a[k];
k = k + 1;
}
j = j + 1;
}
if (b[i] == y) {
x++;
}
i = i + 1;
}
return x;
(3)
// n is the length of array a
// p is an array of integers of length 2
// initial call: method3(a, n-1, p)
// initially p[0] = 0, p[1] = 0
method3(int[] a, int i, int[] p)
if (i == 0) {
p[0] = a[0];
p[1] = a[0];
}
else {
method3(a, i‐1, p);
if (a[i] < p[0]]) {
p[0] = a[i];
}
if (a[i] > p[1]]) {
p[1] = a[i];
}
}
(4)
// initial call: method4(a, 0, n‐1) // n is the length of array a
public static int method4(int[] a, int x, int y)
if (x >= y) {return a[x];}
else {
z = (x + y) / 2; // integer division
u = method4(a, x, z);
v = method4(a, z+1, y);
if (u < v) return u;
else return v;
}
}
Problem 2 (20 points). This problem is a practice of drawing recursion traces of recursive
algorithms.
(1) Draw the recursion trace for the computation of power(2, 5) using the algorithm of Code
Fragment 5.8 in the textbook (page 209)
(2) Draw the recursion trace for the computation of power(2, 13) using the algorithm of Code
Fragment 5.9 in the textbook (page 210)
Examples of recursion traces are shown in Figure 5.10 and Figure 5.12 in the textbook. You may
want to use these examples as models when you draw recursion traces.
Problem 3 (20 points) This problem is about the stack and the queue data structures that are
described in the textbook.
(1) Suppose that you execute the following sequence of operations on an initially empty stack.
Using Example 6.3 in the textbook as a model, complete the following table.