Module: Expertsort::SleepSort

Included in:
Array
Defined in:
lib/expertsort/sorts/sleepsort.rb

Instance Method Summary collapse

Instance Method Details

#sleepsortObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/expertsort/sorts/sleepsort.rb', line 3

def sleepsort
  sorted = []
  threads = []
  semaphore = Mutex.new

  # Reduce potential impact of thread creation time by joining them when all threads have been created
  self.each do |e|
    raise RangeError, "Cannot sleep sort an array with negative elements: #{e}" if e.to_i < 0
    threads << Thread.new do
      sleep e.to_i
      semaphore.synchronize { sorted << e }
    end
  end

  threads.each { |t| t.join }
  sorted
end

#sleepsort!Object



21
22
23
# File 'lib/expertsort/sorts/sleepsort.rb', line 21

def sleepsort!
  self.replace(sleepsort)
end