For each of the algorithm listings below:
Count all assignments to sum
.
public static int someFunc1(int[] numbers) {
int sum = 0;
for (int num : numbers) {
+= num;
sum for (int i = 0; i < 20; i++) {
+= i;
sum }
}
return sum;
}
Count all assignments to sum
.
public static int fun(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
+= numbers[i];
sum for (int j = i; j < numbers.length; j++) {
+= numbers[i] * numbers[j];
sum }
}
return sum;
}
Count assignments to s
.
PROCEDURE DoStuff(numbers1, numbers2)
s <- 0
FOR x IN numbers1 DO
FOR y IN numbers2 DO
IF x < y DO
RETURN 0
ELSE
s <- s + x
ENDIF
ENDFOR
ENDFOR
FOR x IN numbers2 DO
s <- s + x
ENDFOR
RETURN s
Input: A length-n array P containing two-dimensional points.
For example P = [(2.0, 2.3), (1.1, 3.7), (-2.3, 11.0), (4.3, 1.0)]
Output: The area of the smallest triangle that can be created by
selecting three points from P.
Algorithm:
* Create an n x n x n three-dimensional array A.
* Populate each entry A[i][j][k] in A with the area of the triangle
formed from the i'th, j'th and k'th points from P.
* Return the smallest non-zero value from A.
Select an appropriate basic operation.
public static int fun3(ArrayList<Integer> nums1, ArrayList<Integer> nums2) {
int overlap = 0;
for (int num : nums1) {
if (nums2.contains(num)) {
++;
overlap}
}
return overlap;
}
Write an English language description of the value returned by this method:
Worst case or every case?
Exact growth function:
Complexity class:
Use incrementing sum
as the basic operation. For the sake of
simplicity, you may assume that the length of numbers
is a power of 2.
public static int fun4(int[] numbers) {
int sum = 0;
for (int i = numbers.length - 1; i >= 1; i /= 2) {
for (int j = 0; j < numbers.length / 2; j++) {
++;
sum}
}
return sum;
}
public static int fun5(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
flibbert(numbers); // We know that flibbert requires fewer than
// n^2 operations in the worst case.
}
return sum;
}