Algorithm code in Java