Refactor algorithm iteration into smaller methods