1. Suppose that algorithm A takes 1000n3 steps and algorithm B takes 2n steps for a problem of
size n. For what size of problem is algorithm A faster than B (meaning algorithm A has fewer
steps than B)? In your answer describe not only what the answer is but how you arrived at the
answer.
For this question, I have decided to create a Java program that iterates through values of n (from
n=1) comparing the results for each algorithm to find where the program terminates. My termination
criteria is when the algorithm with n^2 steps becomes greater than 1000n^3 steps.
Code
package pkg_1;
public class AlgorithmComparison {
public static void main(String[] args) { int n = 1; while (n>0) { int algorithml = (int) (1000*Math.pow(n,3)); //formula for first algorithm int algorithm2 = (int) (Math.pow(2, n)); //formula for second algorithm
//break the loop and show number of steps of algorithms when B
becomes faster
if (algorithm2>algorithml) { System.out.println("Algorithm A takes lesser time than Algorithm B when n is "+n+" and above"); System.out.println("Algorithm A: "+algorithml); System.out.println("Algorithm B: "+algorithm2); break;
:++u
OUTPUT Algorithm A takes lesser time than Algorithm B when n is 24 and above Algorithm A: 13824000 Algorithm B: 16777216
Output from the console shows that the program terminates when n=24. This means that at 24 steps and above, the first algorithm performs better than the first one.
2. Give the upper bound (big O notation) that you can for the following code fragment, as a function of the initial value of n.
for(int i = 0; i< n; i++) { for(int j = 0; j< i; j++){ //do swap stuff, constant time
Do you think that the lower bound is likely to be the same as the answer you gave for the upper bound? In your response state why or why not.
The statements that perform the "swap stuff"' run at a constant time, say, (c1) for each time they are run. But also, we run the code in the inner-loop, which in turn does the swap stuff, from 0 up to i. This is to say that, if n is 40 and is 1, we "do swap stuff", only once. When I is now 10, the outer loop, will wait for the inner loop to "do swap stuff" just 10 times and. This, mathematically will show that the this approach will take n(n+1)/2 which evaluates to (n^2+n)/2. According to big O, we keep the fastest growing term which gives us an upper bound of O(n^2).