modify binary search code to avoid integer overflow