mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-28 19:58:20 +01:00
commit
b33d30af27
1 changed files with 30 additions and 0 deletions
30
BucketSort.rb
Normal file
30
BucketSort.rb
Normal file
|
@ -0,0 +1,30 @@
|
|||
|
||||
DEFAULT_BUCKET_SIZE = 5
|
||||
|
||||
def bucket_sort(input, bucket_size = DEFAULT_BUCKET_SIZE)
|
||||
print 'Array is empty' if input.empty?
|
||||
|
||||
array = input.split(' ').map(&:to_i)
|
||||
|
||||
bucket_count = ((array.max - array.min) / bucket_size).floor + 1
|
||||
|
||||
# create buckets
|
||||
buckets = []
|
||||
bucket_count.times { buckets.push [] }
|
||||
|
||||
# fill buckets
|
||||
array.each do |item|
|
||||
buckets[((item - array.min) / bucket_size).floor].push(item)
|
||||
end
|
||||
|
||||
# sort buckets
|
||||
buckets.each do |bucket|
|
||||
bucket.sort!
|
||||
end
|
||||
|
||||
buckets.flatten.join(' ')
|
||||
end
|
||||
puts "Enter a list of numbers seprated by space"
|
||||
|
||||
list = gets
|
||||
print bucket_sort(list)
|
Loading…
Add table
Reference in a new issue