Consider the following Java method:
/** Swap A[i] with A[j]
* Precondition: 0 <= i, j < A.length */
public static void swap(int[] A, int i, int j) {
int tmp = A[i];
[i] = A[j];
A[j] = tmp
A}
Which of the following are constant-time operations?
i
from memory in the first line of the method bodytmp
at A[j]
int tmp = A[i]
swap(X, 2, 7)
, where X
is an int[]
Recall our linear search method:
/** Return the index of x in A, or -1 if it doesn't exist. */
public static int linearSearch(int[] A, int x) {
for (int i = 0; i < A.length; i++) {
if (A[i] == x) {
return i;
}
}
return -1;
}
Which of the following are constant-time operations?
return i;
A[i] == x
linearSearch(X, 17)
, where X
is an int[]
Here’s linearSearch
again:
/** Return the index of x in A, or -1 if it doesn't exist. */
public static int linearSearch(int[] A, int x) {
for (int i = 0; i < A.length; i++) {
if (A[i] == x) {
return i;
}
}
return -1;
}
A[]
. In terms of \(N\), give the number of primitive operations performed by a call tolinearSearch
if x
does not appear anywhere in A
. As we did in the examples from the video, follow the convention that any number of constant-time operations performed by a single line of code count as one.linearSearch
based on the above count.x
appears at A[0]
. What is the operation count in this situation?x
will always appear at A[0]
, what would the big-O (asymptotic) runtime of the algorithm be?What’s the best, worst, and average case asymptotic runtime class for the following algorithm? For average case, assume that any value of n
is equally likely.
/** Print some numbers. Pre: n >= 0 */
public static void alg2(int n) {
*= 4;
n if (n % 5 == 0) {
System.out.println("42");
return;
}
while (n > 0) {
System.out.println(n);
/= 2;
n }
}