Created
November 9, 2011 21:59
-
-
Save utsengar/1353235 to your computer and use it in GitHub Desktop.
Java version of Sleep sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* For fun. | |
* Inspiration: http://dis.4chan.org/read/prog/1295544154 | |
* @author zengr | |
* | |
*/ | |
public class Sleepsort { | |
private static int[] inputArray = { 3, 1, 2, 1, 181, 10}; | |
public static void main(String[] args) throws InterruptedException { | |
Sleepsort ss = new Sleepsort(); | |
ss.sleepsort(inputArray); | |
} | |
public void sleepsort(int[] array) throws InterruptedException { | |
for (int val : array) { | |
Thread thread = new Thread(new SleepsortThread(val)); | |
thread.start(); | |
} | |
} | |
} | |
class SleepsortThread implements Runnable { | |
private int val; | |
public SleepsortThread(int val) { | |
this.val = val; | |
} | |
@Override | |
public void run() { | |
try { | |
Thread.sleep(val); | |
System.out.println(val); | |
} catch (InterruptedException e) { | |
// Oops... | |
} | |
} | |
} |
Should use CountDownLatch to start all the threads at same time
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fails for large arrays.
Stacktrace: