CS 3343/3341 Introduction to Algorithms Spring 2012 |
Elementary Recursion Examples |
int fact(int n) { int res = 1; for (int i = n; i >= 1; i--) res *= i; return res; } |
int fact(int n) { if (n == 1) return 1; return n * fact(n-1); } |
// ReverseString: test a recursive method to reverse a String // Uses the String method substring. // s.substring(i) goes from index i to the end. // s.substring(i, j) goes from index i up to but not including index j public class ReverseTest { // recursive string reversal public static String reverse(String s) { if (s.length() == 1) return s; char ch = s.charAt(0); String res = reverse(s.substring(1)) + ch; return res; } // recursive: get rid of unnecessary local variables public static String reverse2(String s) { if (s.length() == 1) return s; return reverse(s.substring(1)) + s.charAt(0); } // recursive: work from the other end public static String reverse3(String s) { if (s.length() == 1) return s; return s.charAt(s.length() - 1) + reverse(s.substring(0, s.length() - 1)); } // NON-RECURSIVE: just concatenate chars in opposite order public static String reverse4(String s) { String res = ""; for (int i = 0; i < s.length(); i++) res = s.charAt(i) + res; return res; } public static void main(String[] args) { String str = "The quick brown fox jumps over the lazy dog."; System.out.println(str); System.out.println(reverse (str)); System.out.println(reverse2(str)); System.out.println(reverse3(str)); System.out.println(reverse4(str)); } } |
Here is the output: The quick brown fox jumps over the lazy dog. .god yzal eht revo spmuj xof nworb kciuq ehT .god yzal eht revo spmuj xof nworb kciuq ehT .god yzal eht revo spmuj xof nworb kciuq ehT .god yzal eht revo spmuj xof nworb kciuq ehT |