Nathan Sprague
$ $
Here is a useful example of recursion:
public static int binarySearch(int[] values, int target,
int start, int end) {
if (start > end) {
return -1;
}
int mid = (start + end) / 2;
if (target == values[mid]) {
return mid;
} else if (target < values[mid]) {
return binarySearch(values, target, start, mid - 1);
} else {
return binarySearch(values, target, mid + 1, end);
}
}
Result:
total equality checks | |
---|---|
1 | 1 |
2 | 2 |
4 | 3 |
8 | 4 |
(For non-powers-of-two
Initial conditions:
Recurrence:
Worst-case recurrence:
Worst-case recurrence:
Step 2: Backward Substitution
(substitute) | ||
(simplify) | ||
(substitute) | ||
(simplify) | ||
(generalize) |
Solve for
Substitute
Applying recurrence:
Applying solution:
count the comparison values[start] == values[end]
public static boolean unique(int[] values, int start, int end) {
if (start >= end) {
return true;
} else if (values[start] == values[end]) {
return false;
} else {
return unique(values, start, end - 1)
&& unique(values, start + 1, end);
}
}
public static boolean unique(int[] values, int start, int end) { if (start >= end) { return true; } else if (values[start] == values[end]) { return false; } else { return unique(values, start, end - 1) && unique(values, start + 1, end); } }
(substitute) | ||
(simplify) | ||
(substitute) | ||
(simplify) | ||
(generalize) | ||
(generalize) |
Solve for
Substitute
Applying recurrence:
Applying solution:
Space, Right Arrow or swipe left to move to next slide, click help below for more details