Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

javascript version for you:

   var numbers  = process.argv.slice(2)
     , output   = []
     , negative = []

   for (var i=0, ln=numbers.length; i<ln; i++){
      var n = +numbers[i]
      setTimeout((function(n){ return function(){
         if (n<0) negative.unshift(n)
         else output.push(n)
         if (output.length + negative.length === numbers.length) {
            return console.log(negative.concat(output))
         }
      }})(n), Math.abs(n)/1000)
   }
Works with negative numbers.

    $ node sleepsort -2 1 0.1 4 -1 7 -3 9
    [ -3, -2, -1, 0.1, 1, 4, 7, 9 ]


your code can be simplified a bit:

    function sleep_sort (inputs) {
      function child (number) {
        setTimeout(function () {console.log(number)}, Math.pow(2,number))
      }

      for (var i = 0; i < inputs.length; ++i)
        child(inputs[i])
    }

    sleep_sort(process.argv.slice(2));


That won't work for numbers < -5 and has a much longer worst case.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: