Lecture 19 Flashcards
One classic application for recursion is for use in
sorting
Merge Sort
merge two pre-sorted arrays.
–If we have two presorted arrays, then the smallest overall element must be in the first slot of one of the two arrays.
–It dramatically reduces the effort needed to find each element in its proper order.
Binary tree code
template class TreeNode { public: K key; V value; TreeNode* left; TreeNode* right; }
Binary tree print
void print(TreeNode* node) { if(node == 0) return; print(node.left); cout << node.value << “ ”; print(node.right); }
Code for using recursion with factorials, but stopping at a certain number.
int factorial(int i, int n) { if(i >= n) return n; else return i * factorial(i+1, n); }
factorial helper method
int factorialStarter(int n) { if(n < 0) throw exception(); else if(n==0) return 1; else return factorial(1, n); }
what is a helper method
It’s so named because its sole reason to
exist is to help setup the needed
parameters and such for the true,
underlying method.
A tail-recursive method is one in which
all of the computation is done during the initial method calls.
factorial tail recursion
int factorial(int part, int n) { if(n == 0 || n == 1) return part; else return factorial(part * n, n-1); }