Improved sort function by doing a 2-stage sort.