I noticed that my recursive Fibonacci algorithm with memoization only works for values greater than 12.
I compared it with someone else's implementation of a method where he also passed an array with it. I thought that passing an array every time, will take too much memory upon re-calling the method thus making the program slower but that was not the case.
I somehow still can't comprehend how my external array is not faster than the normal recursive Fibonacci algorithm. I thought it might be because of the many conditions in my if's that I check that it is slower but I'm not sure.
If possible would you look at my code and tell me what I did wrong or what's going on in the background?
public class Fibonacci2 {
int memory[];
public Fibonacci2(int f) {
if (memory == null) {
memory = new int[f+1];
memory[0] = 0;
memory[1] = 1;
memory[2] = 1;
}
}
public int recursive(int f) {
if (memory[f-1] != 0 && memory[f-2] != 0 && f>2) {
memory[f] = memory[f-1] + memory[f-2];
} else if (memory[f-1] == 0 && memory[f-2] != 0 && f>2) {
memory[f] = recursive(f-1) + memory[f-2];
} else if (f>2) {
memory[f] = recursive(f-1) + recursive(f-2);
}
return memory[f];
}
}
public class Fibonacci1 {
public Fibonacci1() {}
public int recursive(int f) {
if (f > 2) {
return recursive(f-1) + recursive(f-2);
} else {
return 1;
}
}
}
public class Main {
public static void main(String[] args) {
int fibo = 12;
Fibonacci1 fiboEx1 = new Fibonacci1();
Fibonacci2 fiboEx2 = new Fibonacci2(fibo);
int a = fiboEx1.recursive(fibo);
long start = System.nanoTime();
long stop = System.nanoTime();
System.out.println("fibo of " + fibo + " is " + a);
System.out.println("Fibonacci time without memorization: " + (stop-start));
int b = fiboEx2.recursive(fibo);
start = System.nanoTime();
stop = System.nanoTime();
System.out.println("fibo of " + fibo + " is " + b);
System.out.println("Fibonacci time with memorization: " + (stop-start));
}
}