Counting Sort

Sort an array of non-negative integers using counting sort for linear time performance.

Code

Algorithms
count = Array.new(arr.max + 1, 0)
arr.each { |x| count[x] += 1 }
result = []
count.each_with_index { |c, i| c.times { result << i } }
result

Parameters

Array of integers

Server

More Ruby Snippets