MidTerm+Review+Chapter+13+Quiz (1)

advertisement
David Zeng
Chapter 13 Review
1. This program calculates the first 10000 primes.
Determine the Time Complexity of This Code Segment
public int[] primes = new int[10000];
public void run() {
boolean isPrime;
primes[0] = 2;
primes[1] = 3;
int counter = 4;
while (primes.length < 10000) {
isPrime = true;
for (int prime : primes) {
if (counter % prime == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes[primes.length - 1] = counter;
}
counter++;
}
answer = primes[9999];
} //Source of Code: David Zeng; Problem comes from projecteuler.net
Note: n/1000000000 is still O(n)
(a)
(b)
(c)
(d)
O(1)
O(n log n)
O(n^10000)
O(n^2)
2. Identify what needs to be fixed about this code segment
public int bad (int n){
if(n == 1)
return 1;
else
return n*bad(n-42);
}
(a)
In order for a recursive method to work, it must be static and must call itself as a class method.
(b)
For the else statement, it returns both an integer and another method! This is Illegal in Java!
(c)
This “n==1” should be changed to “n<1”! Stack Overflow Error will occur otherwise if the value
of the number given is not equivalent to 1 mod 42
(d)
The reference to int n is constantly passed through the methods, in every method the value of n
is changed, throwing off the results!
3. Read the following method.
public void lawl(int n){
if(n>0){
lawl(n-2);
System.out.print(n);
Lawl(n-1);
}
}
What is the output if the call lawl(3) is done?
a) 1321
b) 321321
c) 32121
d) 1123
4. Assuming the array is already sorted, why will this code not work?
public class Student {
public static final int COMPARABLE_VALUE_OF_OBJECT;
public int testScores;
public Student(int t, int test){
COMPARABLE_VALUE_OF_OBJECT = t;
}
}
public int search(Student[] stuArray,Student search, int left,int right){
if(left>right)
return -1;
else{
int midPoint = (left+right)/2;
if(stuArray[midPoint]==searchValue){
return midPoint;
}
else if(stuArray[midPoint]<searchValue)
return search(stuArray,search,midPoint+1,right);
else
return search(stuArray,search,left,midpoint-1);
}
}
}
Hint: The variable in all capital letters may or may not be irrelevant
Now, rewrite the classes so that this program can successfully binary search through the student array.
Download