Fix sort and refactor complexity