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:
n | total equality checks |
---|---|
1 | 1 |
2 | 2 |
4 | 3 |
8 | 4 |
(For non-powers-of-two ⌊log2n⌋+1)
Initial conditions:
W(1)= ??
W(1)=1
Recurrence:
W(n)=??
W(n)=1+W(n/2)
Worst-case recurrence:
W(1)=1
W(n)=1+W(n/2)
Worst-case recurrence:
W(1)=1
W(n)=1+W(n/2)
Step 2: Backward Substitution
W(1)=1
W(x)=1+W(x/2)
W(n) | =1+W(n/2) | |
=1+1+W((n/2)/2) | (substitute) | |
=2+W(n/4) | (simplify) | |
=2+1+W((n/4)/2) | (substitute) | |
=3+W(n/8) | (simplify) | |
... | ||
=i+W(n2i) | (generalize) |
Solve for i that results in initial condition:
n2i=1
n=2i
i=log2n
Substitute log2n for i:
W(n)=log2n+1
Applying recurrence:
W(1)=1
W(2)=1+W(1)=1+1=2
W(4)=1+W(2)=1+2=3
Applying solution:
W(1)=log21+1=0+1=1
W(2)=log22+1=1+1=2
W(4)=log44+1=2+1=3
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); } }
W(1)=0
W(n)=1+2W(n−1)
W(1)=0
W(x)=1+2W(x−1)
W(n) | =1+2W(n−1) | |
=1+2(1+2W((n−1)−1) | (substitute) | |
=1+2+4W(n−2) | (simplify) | |
=1+2+4(1+2W((n−2)−1) | (substitute) | |
=1+2+4+8W(n−3) | (simplify) | |
... | ||
=∑i−1j2j+2iW(n−i) | (generalize) | |
=2i−1+2iW(n−i) | (generalize) |
Solve for i that results in initial condition:
n−i=1
i=n−1
Substitute n−1 for i:
W(n)=2n−1−1+2n−1×0=2n−1−1
Applying recurrence:
W(1)=0
W(2)=1+2W(0)=1+0=1
W(3)=1+2W(1)=1+1=2
W(4)=1+2W(2)=1+2=3
Applying solution:
W(1)=21−1−1=0
W(2)=22−1−1=1
W(3)=23−1−1=3