Big O Notation
Big O Notation
HW #9
1. Question 1
a. O(nlogn)
b. O(nlogn)
c. O(nlogn)
2. Question 2
a. the first element
i. O(n^2)
ii. O(n^2)
iii. O(nlogn)
b. the larger of the first two distinct elements
i. O(n^2)
ii. O(n^2)
iii. O(nlogn)
c. a random element
i. O(nlogn)
ii. O(nlogn)
iii. O(nlogn)
d. the average of all elements in the set
i. O(nlogn)
ii. O(nlogn)
iii. O(nlogn)
3. Question 3
a. int i = left - 1
int j = right
int p = left - 1
int q = right
int pivotElem = element in array for pivot
while(true) {
while(array[++i] < pivotElement)
while(array[--j] > pivotElement)
if(i<=j) {
break;
}
else {
swap(array[i], array[j])
}
if(array[i] == pivotElement) {
swap(array[i], array[++p];
}
if(array[j] == pivotElement) {
swap(array[j], array[--q]);
}
}
j=i-1
for(int k = left; k < p; k++, j--) {
swap(array[k], array[j])
}
i=i+1
for(int k = right-1; k > q; k--, i++) {
swap(array[i], array[k]);
}
4. S, G, D, A, B, C, H, E, I, F, C, T
5. Going from a to b cost 5 while going from a to c to b cost 3 but Dijkstra would mark a to
b as the shortest path because it sees the cost from a to c greater than a to b and marks
them both known without going through a to c to b to check.
6. You can modify the algorithm by making an array “count” that holds all vertex and each
vertex in the list points to the number of distinct paths from vertex v to vertex being
looked up in array. When vertex v is marked as known adjacency list traversed to find
next shortest distance, w is a vertex on the adjacency list. If distance from v plus v to w
equals distance to w the you increment count[w] by count[v] because all shortest path in
count of v give a shortest path to vertex w also. If the distance from v plus distance from
v to w is less than distance to w then count[w] is set equal to count[v] because all shortest
paths to w are invalid so replaced with shortest paths from v.
7. Question 7
a. You can find the point of intersection on the xy plane using the x and y
coordinates if they don’t intersect they are unrelated otherwise the stick with the
higher z value at the point of intersection is above the other.
b. To determine if you can pick up all sticks you have a list of all the sticks in the
pile and loop through the list to find the stick on top by picking the first stick and
seeing if there is one above it, at the end of the list the one determined to be on
top remove it and start over again. Keep track of sticks that are top of one another
so if the first stick S1 is below stick 2 then keep track of chain and if any other
stick is currently above the current stick to be removed but already in the chain
there is a cycle and therefore cannot pick up all sticks.