Java algorithm for searching