Fixed Sorting. Added Randomization for ties.