fixed the sorting and also optimized code