Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 29th, 2012  |  syntax: None  |  size: 0.60 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. --sleep sort
  2.  
  3. function sleepsort(arr)
  4.     local res, thread = {}, {}
  5.     local nthreads = #arr
  6.  
  7.     for i = 1, #arr do
  8.         thread[i] = coroutine.create(function()
  9.             for n=arr[i], 0, -1 do coroutine.yield() end
  10.             nthreads = nthreads - 1
  11.             thread[i] = nil
  12.             res[#res+1] = arr[i]
  13.         end)
  14.     end
  15.     while nthreads > 0 do
  16.         for i = 1, #arr do
  17.             if thread[i] then coroutine.resume(thread[i]) end
  18.         end
  19.     end
  20.     return res
  21. end
  22.  
  23. math.randomseed(os.time())
  24. local arr = {}
  25. for i = 1,10 do arr[i] = math.random(1,99) end
  26. print(unpack(sleepsort(arr)))