Recursion
Recursion Notes & HW
Recursive Method
A method that calls itself. Similar to recursive functions in math that continuously calls itself to get an output value. One base case that halts recursion an once recursive call. Each recursion has its own local variables and thus act independently of itself. Parameters take progress. Can be replaced w an iterative and give same result so acts like loop that traverses strings array arraylist. There's always an if statement to stop the call. Can have multiple instances of recursion within itself.
Binary Search
Taking array and starting at midpoint. It is one of the ,ost efficient searches w complexity n*log(n). find the midpoint and iterate through to compare midpoint to bounds and checking if target is greater/less. Way to find how to not to binary search.
Merge Sort
Can be used to sort array list which uses Divide and Conquer algorithm Divides them in half and then calls itself into different halves and sorts them. It then merges the two sorted halves into one list. Recursion to divide and compare left and right sides.
Visualizing Recursion
One way is building a recursive tree making note of each recursive case. This makes it easy to visualize the call and track the conditions of the recursion.
public static void main(String[] args){
System.out.println(equation(8));
}
public static int equation(int a){
if(a <= 5){
return 12;
}
return equation(a-2) * equation(a-1);
}
main(null);