Replaced a loop with binsearch