moved sorting inside sort fuction