Added time counting function and decreased number of times sort is performed (big time sink).