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
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].
a[i]
val
val - a[i]