Monday, 20 June 2011

Java Sleep Sort - For The Lulz

Strictly for the lulz, here is an implementation of Sleep Sort, first seen on 4chan.

SleepSort.java

package sleepsort;

import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class SleepSort {

  public static void main(final String[] args) throws Exception {

    int[] numbers = {90, 80, 70, 60, 50, 40, 30, 20, 10};
    int[] sortedNumbers = sort(numbers);
    System.out.println(Arrays.toString(sortedNumbers));
  }

  private static int[] sort(final int[] numbers) throws InterruptedException, ExecutionException {

    ExecutorService executor = Executors.newFixedThreadPool(numbers.length);
    ExecutorCompletionService<Integer> ecs = new ExecutorCompletionService<Integer>(executor);
    for (int number : numbers) {
      ecs.submit(new SleepSortCallable((number)));
    }

    int[] sortedNumbers = new int[numbers.length];
    for (int i = 0; i < sortedNumbers.length; i++) {
      sortedNumbers[i] = ecs.take().get();
    }

    executor.shutdown();

    return sortedNumbers;
  }

  private static class SleepSortCallable implements Callable<Integer> {

    private final int number;

    public SleepSortCallable(final int number) {
      this.number = number;
    }

    @Override
    public Integer call() throws Exception {
      Thread.sleep(number);
      return number;
    }
  }
}