-
Notifications
You must be signed in to change notification settings - Fork 267
/
bucket_sort.rb
47 lines (38 loc) · 983 Bytes
/
bucket_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
# frozen_string_literal: true
require_relative "./insertion_sort"
# Sort an array using the BucketSort algorithm
class BucketSort
attr_reader :array_sorted
def initialize
@array_sorted = []
@insertion = InsertionSort.new
end
def init(array)
bucket_sort(array, array.length)
end
private
def bucket_sort(array, bucket_size)
return nil if array.empty?
min, max = array.minmax
bucket_count = ((max - min) / bucket_size).floor + 1
buckets = Array.new(bucket_count)
(0..buckets.length - 1).each do |i|
buckets[i] = []
end
(0..array.length - 1).each do |i|
buckets[((array[i] - min) / bucket_size).floor].push(array[i])
end
array.clear
(0..buckets.length - 1).each do |i|
@insertion.init(buckets[i])
buckets[i].each do |value|
array.push(value)
end
end
@array_sorted = array
end
end
# test
bu_s = BucketSort.new
bu_s.init([1, 4, 10, 2, 3, 32, 0])
p bu_s.array_sorted