Recently, I saw a sleepsort algorithm on the Internet (written using shell scripts): the code is as follows:
----------------------------------------------------------------------------
#!/bin/bashfunction f() { sleep "$1" echo "$1"}while [ -n "$1" ]do f "$1" & shiftdonewait----------------------------------------------------------------------------- |
The usage is as follows:
./Sleepsort. Bash 1 4 7 3 8 9 2 6 5
| Analysis: the core idea is to determine the sleep time based on the size of the data read, so that the data size can be correctly sorted. |
Negative or floating-point numbers have bugs.
Some netizens improved this algorithm:
The negative number solution is: X/2 + maxint/2 (the time may be quite long, but it still works ). For floating point numbers, see the following code.
----------------------------------------------------------------------------
#!/bin/bash function f() { sleep $( echo "($2 - 1) + $1 / 10 ^ $2" | bc -l) echo "$1" } while [ -n "$1" ] do f "$1" $( echo -n "$1" | wc -c) & shift done wait---------------------------------------------------------------------------- The winner has implemented the Javascript version: accept :---------------------------------------------------------------------------
function sleepsort() { for ( var i = 0, il = arguments.length; i < il; i++) { ( function (args, index) { setTimeout( function () { document.body.innerHTML += args[index] + ', ' ; }, args[index]); }(arguments, i)); } };-----------------------------------------------------------------------------
Based on this core idea, the implementation method of Java version is as follows: extends public class sleepsort {public static void main (string [] ARGs) {int [] ints =, 2, 6, 5}; sortthread [] sortthreads = new sortthread [ints. length]; for (INT I = 0; I <sortthreads. length; I ++) {sortthreads [I] = new sortthread (ints [I]);} For (INT I = 0; I <sortthreads. length; I ++) {sortthreads [I]. start () ;}} class sortthread extends thread {int MS = 0; Public sortthread (int ms) {This. ms = MS;} public void run () {try {sleep (MS * 10 + 10);} catch (interruptedexception e) {// todo auto-generated Catch Block E. printstacktrace ();} system. out. print (MS + "") ;}} milliseconds "");}}-------------------------------------------------------------------------------------------