Algorithm implement in java