updated sorting function