Optimized sorting function (7h > 30min)