Fixed the sorting algorithm
Cleaned up the result loop