Alogrithm in Java