Implemented the sort function for pagination.