
Sorting Algorithm

This is a sorting algorithm.   It may be applied to a set of data in order to sort it.    
For comparing various sorts, see compare sorts.  
For other sorting algorithms,   see sorting algorithms,   or:

O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort


In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.

Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.

Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.

' version 21-10-2016
' compile with: fbc -s console
' compile with: fbc -s console -exx (for bondry check on the array's)
' not very well suited for large numbers and large array's
' positive numbers only 
 
Sub sandman(sleepy() As ULong)
    Dim As Long lb = LBound(sleepy)
    Dim As Long ub = UBound(sleepy)
    Dim As Long i, count = ub
    Dim As Double wakeup(lb To ub)
    Dim As Double t = Timer
 
    For i = lb To ub
        wakeup(i) = sleepy(i) +1 + t
    Next
 
    Do
        t = Timer
        For i = lb To ub
            If wakeup(i) <= t Then
                Print Using "####";sleepy(i);
                wakeup(i) = 1e9 ' mark it as used
                count = count -1
            End If
        Next
        Sleep (1 - (Timer - t)) * 300, 1 ' reduce CPU load
    Loop Until count < lb
 
End Sub
 
' ------=< MAIN >=------
 
Dim As ULong i, arr(10)
Dim As ULong lb = LBound(arr)
Dim As ULong ub = UBound(arr)
 
Randomize Timer
For i = lb To ub -1 ' leave last one zero
    arr(i) = Int(Rnd * 10) +1
Next
 
Print "unsorted  ";
For i = lb To ub
    Print Using "####";arr(i);
Next
Print : Print
 
Print "  sorted  ";
sandman(arr())
 
Print : Print
 
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End