Algorithm in Java