DEV Community

Discussion on: Write better code: Day 4 - Sorted scores

Collapse
 
arjunrajkumar profile image
Arjun Rajkumar

The problem asked to do this in lesser than O[nlogn] time.
Counting sort has O[n] time, so applied that straight.

def sort_scores(unsorted_scores, highest_score)
  counts = [0] * (highest_score + 1)

  unsorted_scores.each do |score|
    counts[score] += 1
  end

  sorted_score = []
  highest_score.downto(1).each do |score|
    count = counts[score]

    (0...count).each do |i|
      sorted_score << score
    end
  end

  sorted_score
end