Algorithm implementation in Java