COMP 210
Lecture 6
1
Announcements
2
Quiz 01 Topics
3
Big-O Continued
4
Code Analysis: Loops (2/2)
for (i=0; i<N; i++) { // O(# iterations) = O(N)
// O(loop body) = max of:
int prefix_sum = 0; // O(1)
for (j=0; j<i; j++) { // O(inner for loop)
prefix_sum += data[j];
System.out.println(“Sum of first “ + i
+ “ items: “ + prefix_sum);
}
}
5
Code Analysis: Divide and Conquer Recursion (1/2)
6
Code Analysis: Divide and Conquer Recursion (2/2)
Total for recursion: O(log N) * O(N) = O(N log N)
static int recursiveSum(int start, int end, int[] data) {
if (start == end) {
return data[start];
} else {
int first_half_sum = recursiveSum(start, (start+end)/2, data);
int second_half_sum = recursiveSum(((start+end)/2)+1, end, data);
return first_half_sum + second_half_sum;
}
}
7
Code Analysis: Divide and Conquer Recursion (2/2)
static int recursiveSum(int start, int end, int[] data) {
if (start == end) {
return data[start];
} else {
int first_half_sum = recursiveSum(start, (start+end)/2, data);
int second_half_sum = recursiveSum(((start+end)/2)+1, end, data);
return first_half_sum + second_half_sum;
}
}
8
Beware Exponential Recursion
static int fib(int n) {
if (n < 2) {
return 1;
} else {
return fib(n-2) + fib(n-1);
}
}
9
Example Problem 1
public static findMax(int[] data) {
int max = data[0];
for (int i=0; i<data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
10
Example Problem 2
public static long fun(int N) {
int x = 2;
for (int i=N; i>0; i--) {
for (int j=i; j<i+8; j++){
for (int k=0; k<i; k++) {
x += i-j*k
}
}
}
return x;
}
11
Example Problem 3
12
Object -- The Universal Reference Type
13
Object: the universal reference type (and null)
14
Generics
15
Parameterized Types
16
An Aside: Method Access
Assumptions: Person is an interface that has 2 methods -- breathe and eat. Student implements this interface. Additionally, Student has another method called study.
Person kaki = new Student(); // ok
kaki.breathe(); // ok
kaki.study(); // bad!
Student adin = new Student();
adin.study(); // ok
adin.eat(); // ok
17
Lists
18
The Behavior of List
19
Axiomatic Specification
20
Functional Specification of List<E>
21
Canonical Operations
22
Axioms of Behavior
23
Axioms of Behavior
24
Axioms of Behavior
25
Axioms of Behavior
26
Implementations of List
27
List<T>
28
Concrete Implementation of List
29
Linked List
30
Array List vs. Linked List on the Heap
31