-
Notifications
You must be signed in to change notification settings - Fork 266
/
counting_sort.rb
53 lines (43 loc) · 1001 Bytes
/
counting_sort.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# frozen_string_literal: true
# Sort an array using the CountSort algorithm
class CountSort
attr_reader :array_sorted
def initialize
@array_sorted = []
end
# min_max[0] = menor valor
# min_max[1] = maior valor
def init(array)
min_max = array_max_min(array)
count_sort(array, min_max[0], min_max[1])
end
private
def array_max_min(array)
array.minmax
end
def count_sort(array, min, max)
return "algo deu errado pqp" if min > max
n = max - min + 1
size = array.length
aux = Array.new(size)
count = Array.new(n, 0)
(0...size).each do |i|
count[array[i] - min] += 1
end
(1...n).each do |i|
count[i] += count[i - 1]
end
(0...size).each do |i|
aux[count[array[i] - min] - 1] = array[i]
count[array[i] - min] -= 1
end
(0...size).each do |i|
array[i] = aux[i]
end
@array_sorted = array
end
end
# test
c_s = CountSort.new
c_s.init([1, 4, 10, 2, 3, 32, 0])
p c_s.array_sorted