Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Created November 23, 2014 17:18
Show Gist options
  • Save rshepherd/5fa5a3b75c7a156a2d7c to your computer and use it in GitHub Desktop.
Save rshepherd/5fa5a3b75c7a156a2d7c to your computer and use it in GitHub Desktop.
Code snippets from recursion lecture
public class Recursion {
public static class ExampleOne
{
public static void main (String args[])
{
count(0);
}
public static void count (int index)
{
System.out.println(index);
if (index < 2)
count(index+1);
}
}
public static class ExampleTwo
{
public static void main (String args[])
{
upAndDown(1);
}
public static void upAndDown (int n)
{
System.out.print ("\nLevel-up: " + n);
if (n < 4)
upAndDown (n+1);
System.out.print ("\nLevel-down: " + n);
}
}
public static class Factorial
{
public static void main (String args[])
{
for (int i = 1; i < 10; i++)
System.out.println ( i + "! = " + findFactorial(i));
}
public static int findFactorial (int number)
{
if (number <= 1)
return 1;
else
return number * findFactorial(number-1);
}
}
public static class TailRecursion {
public static void main (String args[])
{
printName(5);
}
public static void printName(int level){
if( level <= 0 )
return;
System.out.println("Smith");
printName(--level);
}
}
public static class Fibonacci
{
public static void main (String args[])
{
int number = 5;
long fibonacciValue = fibonacci( number );
System.out.println (fibonacciValue);
}
public static long fibonacci( long n )
{
if ( n == 0 || n == 1 )
return n;
else
return fibonacci( n - 1 ) + fibonacci( n - 2 );
}
static long [] array = new long [100];
public static long memoizedFibonacci( long n )
{
if ( n == 0 || n == 1 )
return n;
else if (array[(int)n] != 0)
return array[(int)n];
else
{
array[(int)n] = fibonacci( n - 1 ) + fibonacci( n - 2 );
return array[(int)n];
}
} // end method fibonacci
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment