排序算法——睡眠排序(Sleep sort)【代码实现】

Bash

function sleep_and_echo {
  sleep "$1"
  echo "$1"
}
 
for val in "$@"; do
  sleep_and_echo "$val" &
done
 
wait

C

#include 
#include 
#include 
#include 
 
int main(int c, char **v)
{
        while (--c > 1 && !fork());
        sleep(c = atoi(v[c]));
        printf("%d\n", c);
        wait(0);
        return 0;
}

C++

#include 
#include 
#include 
#include 
 
int main(int argc, char* argv[]) {
  std::vector<std::thread> threads;
 
  for (int i = 1; i < argc; ++i) {
    threads.emplace_back([i, &argv]() {
      int arg = std::stoi(argv[i]);
      std::this_thread::sleep_for(std::chrono::seconds(arg));
      std::cout << argv[i] << std::endl;
    });
  }
 
  for (auto& thread : threads) {
    thread.join();
  }
}

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
 
class Program
{
    static void ThreadStart(object item)
    {
        Thread.Sleep(1000 * (int)item);
        Console.WriteLine(item);
    }
 
    static void SleepSort(IEnumerable<int> items)
    {
        foreach (var item in items)
        {
            new Thread(ThreadStart).Start(item);
        }
    }
 
    static void Main(string[] arguments)
    {
        SleepSort(arguments.Select(int.Parse));
    }
}

Dart

import 'dart:async';
 
Future> sleepsort(List input) {
  List> tasks = [];
  List result = [];
  for (int i in input) {
    tasks.add(new Future.delayed(new Duration(seconds: i), () {
      result.add(i);
    }));
  }
  return Future.wait(tasks).then((_) {
    return result;
  });
}
 
sleepsort.sleepsort([3, 1, 2]).then((List sorted) {
  print(sorted);
});

Go

package main
 
import (
	"fmt"
	"log"
	"os"
	"strconv"
	"time"
)
 
func main() {
	out := make(chan uint64)
	for _, a := range os.Args[1:] {
		i, err := strconv.ParseUint(a, 10, 64)
		if err != nil {
			log.Fatal(err)
		}
		go func(n uint64) {
			time.Sleep(time.Duration(n) * time.Millisecond)
			out <- n
		}(i)
	}
	for _ = range os.Args[1:] {
		fmt.Println(<-out)
	}
}

Java

import java.util.concurrent.CountDownLatch;
 
public class SleepSort {
	public static void sleepSortAndPrint(int[] nums) {
		final CountDownLatch doneSignal = new CountDownLatch(nums.length);
		for (final int num : nums) {
			new Thread(new Runnable() {
				public void run() {
					doneSignal.countDown();
					try {
						doneSignal.await();
 
						//using straight milliseconds produces unpredictable
						//results with small numbers
						//using 1000 here gives a nifty demonstration
						Thread.sleep(num * 1000);
						System.out.println(num);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}
	public static void main(String[] args) {
		int[] nums = new int[args.length];
		for (int i = 0; i < args.length; i++)
			nums[i] = Integer.parseInt(args[i]);
		sleepSortAndPrint(nums);
	}
}

JavaScript

Array.prototype.timeoutSort = function (f) {
	this.forEach(function (n) {
		setTimeout(function () { f(n) }, 5 * n)
	});
}

Kotlin

// version 1.1.51
 
import kotlin.concurrent.thread
 
fun sleepSort(list: List<Int>, interval: Long) {
    print("Sorted  : ")
    for (i in list) {
        thread {
            Thread.sleep(i * interval)
            print("$i ")
        }
    }
    thread { // print a new line after displaying sorted list
        Thread.sleep ((1 + list.max()!!) * interval)
        println()
    }
}
 
fun main(args: Array<String>) {
   val list = args.map { it.toInt() }.filter { it >= 0 } // ignore negative integers
   println("Unsorted: ${list.joinToString(" ")}")
   sleepSort(list, 50)
}

Python

from time import sleep
from threading import Timer
 
def sleepsort(values):
    sleepsort.result = []
    def add1(x):
        sleepsort.result.append(x)
    mx = values[0]
    for v in values:
        if mx < v: mx = v
        Timer(v, add1, [v]).start()
    sleep(mx+1)
    return sleepsort.result
 
if __name__ == '__main__':
    x = [3,2,4,7,3,6,9,1]
    if sleepsort(x) == sorted(x):
        print('sleep sort worked for:',x)
    else:
        print('sleep sort FAILED for:',x)
#!/usr/bin/env python3
from asyncio import run, sleep, wait
from sys import argv
 
async def f(n):
    await sleep(n)
    print(n)
 
if __name__ == '__main__': 
    run(wait(list(map(f, map(int, argv[1:])))))

Ruby

require 'thread'
 
nums = ARGV.collect(&:to_i)
sorted = []
mutex = Mutex.new
 
threads = nums.collect do |n|
  Thread.new do
    sleep 0.01 * n
    mutex.synchronize {sorted << n}
  end
end
threads.each {|t| t.join}
 
p sorted

Swift

import Foundation
 
for i in [5, 2, 4, 6, 1, 7, 20, 14] {
    let time = dispatch_time(DISPATCH_TIME_NOW,
        Int64(i * Int(NSEC_PER_SEC)))
 
    dispatch_after(time, dispatch_get_main_queue()) {
        print(i)
    }
}
 
CFRunLoopRun()

更多代码,敬请期待!
整理自网络。

你可能感兴趣的:(排序算法,代码实现)