How to implement java Sleep sorting algorithm
This article mainly explains "how to implement the java sleep sorting algorithm". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to implement the java sleep sorting algorithm.
Take a look at the following picture first:
Really impressive, this sorting, there are both multithreading, sorting, and lambda expressions, but this is the C# version, as a Java enthusiast, of course, to try the Java version, nonsense, on the code
/ * * @ author Marblog * / public class Main {public static void main (String [] args) {int [] nums = new int [] {235,233,110,789, 5,0,1}; for (int item: nums) {new Thread (()-> {try {Thread.sleep (item)) } catch (InterruptedException e) {e.printStackTrace ();} System.out.println (item);}) .start ();}
The code is very rough, a lot of bug. such as
(1) I can't handle negative numbers.
(2) for example, there will be errors when the input data are very similar.
(3) when entering a lot of data, these threads can not be regarded as starting at the same time and so on.
For (1), you can map the input to time with a function that is always positive.
(2) you can multiply the coefficient to enlarge the difference between the data, but you still can't handle the duplicate data.
(3) try to make the algorithm truly parallel on multiple physical cores.
Running result
This is a very neurotic algorithm, and you can't think of a cerebral thrombus in ten years.
The principle is to open a lot of threads, the number of threads is equal to the number of elements you want to sort, let them output in the original array order, let the thread sleep in the process, the length of sleep corresponds to the size of the element itself, so the bigger the sleep, the longer you sleep.
At this point, I believe you have a deeper understanding of "how to implement the java sleep sorting algorithm". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!