added early exit for sorting function