made sorting optional in the function