Unit 10 Recursion
- Definition: solving a problem by breaking it down into smaller instances of the exact same problem
- Divides problem into smaller pieces and calls itself for each piece
- Each Recursive Method has a base case and recursive method
- Base case: condition that terminates the problem, the last time the function is called
- Recursive case is each time the function is called with a smaller version of the problem
- Recursion is easier to read
- Trade Offs:
- Speed and memory
- Recursion requires a call stack
- Call stack: keeps track of all previous function calls
- results of recursive calls are needed
- Binary Search repeatedly divides the list in two
- must be presorted
public int binarySearch(int[] array, int target) {
int low = 0;
int high = array.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (array[mid] == target) {
return mid;
} else if (target < array[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
public int binarySearch(int[] array, int target, int low, int high) {
if (low > high) {
return -1;
}
int mid = (low + high) / 2;
if (array[mid] == target) {
return mid;
} else if (target < array[mid]) {
return binarySearch(array, target, low, mid - 1);
} else {
return binarySearch(array, target, mid + 1, high);
}
}