Taken from Introduction to Algorithms
Describe a Θ(n lg n)-time algorithm that, given a set S of n integers and another integer x, determines whet
I do think I have spotted a minor bug in your implementation, but testing should uncover that one quickly.
The approach looks valid, and will reach the desired performance. You might simplify it by replacing the iterative binary search with a scan through the array, in effect replacing the binary search by a linear search that resumes where the previous linear search left off:
int j = a.length - 1;
for (int i = 0; i < a.length; i++) {
while (a[i] + a[j] > val) {
j--;
}
if (a[i] + a[j] == val) {
// heureka!
}
}
This step is O(n). (Proving that is left as an exercise for you.) Of course, the entire algorithm still takes O(n log n) for the merge sort.
This is correct; your algorithm will run in O(n lg n) time.
There is a better solution: your logic for calculating diff is incorrect. Regardless of whether a[i]
is greater than or less than val
, you still need diff to be val - a[i]
.