Java Algorithm Implementation