General algorithm implementation