Implementation of sort