For each of the following algorithms, give its worst-case and best-case asymptotic runtime class.
Let \(n\) = side_length
and give your answer in terms of \(n\).
/** Print a multiplication table listing the pairwise products
* of all integers in 0..side_length. */
public static void multTable(int side_length) {
for (int i = 0; i < side_length; i++) {
for (int j = 0; j < side_length; j++) {
System.out.print(i*j);
System.out.print(" ");
}
System.out.println();
}
}
Give your answer in terms of n
.
/** Print n sets of nested parentheses. Example: nest(4) prints (((())))
* Pre: n >= 0. */
public static void nest(int n) {
for (int i = 0; i < n; i++) {
System.out.print("(");
}
for (int i = 0; i < n; i++) {
System.out.print(")");
}
System.out.println();
}
Let \(n\) = A.length
and give your answer in terms of \(n\).
/** Print the first min(10, A.length) elements of A. */
public static void firstTen(int[] A) {
int i = 0;
while (i < 10 && i < A.length) {
System.out.print(A[i]);
+= 1;
i }
}
Give your answer in terms of n
.
/** Return the number of times n is evenly divisible by 7 */
public static void sevens(int n) {
int k = n;
int count = 0;
while (k > 1 && k % 7 == 0) {
/= 7;
k ++;
count}
return count;
}
Let \(n\) = height
and give your answer in terms of \(n\).
/** Print an ASCII art picture of a width-6 ladder with the given number of rungs.
* For example, printLadder(4) prints:
* |----|
* |----|
* |----|
* |----|
*/
public static void printLadder(int height) {
for (int i = 0; i < height; i++) {
System.out.print("|");
for (int j = 0; j < 4; j++) {
System.out.print("-");
}
System.out.println("|");
}
}
Assume that this method has access to the linearSearch
method we’ve discussed. Let \(m\) = A.length
and give your answer in terms of n
and \(m\).
/** Return the number of integers in 0..n that appear in A. */
public static int numFirstN(int[] A, int n) {
int count = 0;
for (int i = 0; i < n; i++) {
if (linearSearch(A, i) >= 0) {
++;
count}
}
return count;
}
Let \(n\) = side_length
and give your answer in terms of \(n\).
/** Print a lower-triangular multiplication table listing the products i*j
* for all pairs i <= j in 0..side_length. */
public static void multTable(int side_length) {
for (int i = 0; i < side_length; i++) {
for (int j = 0; j < side_length; j++) {
if (i <= j) {
System.out.print(i*j);
System.out.print(" ");
}
}
System.out.println();
}
}
Give your answer in terms of n
.
public static void nonsense(int n) {
int i = n/2;
int j = i;
while (i > 0) {
/= 2;
i }
while (j > 0) {
-= 2;
j }
}