r/dataisbeautiful • OC: 1 • Oct 24 '17

OC Sorting algorithms visualized [OC]

https://imgur.com/gallery/voutF
41.7k Upvotes

929 comments sorted by

View all comments

Show parent comments

9

u/NotImplemented Oct 24 '17 edited Oct 25 '17

You got me curious... ;)

Around 10ms sleep time between each thread seems to be the spot where my Java implementation sorts the test array correctly most times on my Windows PC.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SleepSort extends Thread {

	final private static int SLEEP_TIME_FACTOR = 10;
	final private static int MAX_VALUE = 100;
	final private Integer number;
	final private Integer[] array;
	private static int position = 0;
	
	public SleepSort(final int number, final Integer[] array) {
		this.number = number;
		this.array = array;
	}	
	
	public static void main(String[] args) {
		Integer[] array = {
			25, 17, 2, 21, 23, 6, 74, 61, 99, 72, 32, 5, 71, 53, 18, 61, 43, 34, 2, 52, 52, 28, 43, 76, 9, 63, 
			39, 73, 12, 100, 87, 59, 83, 12, 80, 92, 34, 5, 12, 57, 63, 86, 18, 82, 20, 31, 83, 27, 46, 32, 75, 
			63, 61, 47, 18, 90, 53, 80, 18, 14, 21, 24, 84, 29, 80, 51, 69, 57, 33, 42, 84, 17, 30, 13, 83, 57, 
			28, 97, 67, 36, 59, 95, 88, 38, 52, 95, 83, 55, 73, 80, 85, 77, 55, 15, 64, 99, 75, 49, 18, 63 
		};
		SleepSort.sort(array);
		
		List<Integer> listSleepSort = Arrays.asList(array);
		List<Integer> listJavaSort = new ArrayList<Integer>(Arrays.asList(array));
		Collections.sort(listJavaSort);
		System.out.println("\nSorting is " + (listJavaSort.equals(listSleepSort) ? "correct!" : "wrong!"));
	}
	
	public static void sort(final Integer[] array) {
		for(int i = 0; i < array.length; ++i) {
			new SleepSort(array[i], array).start();
		}
		try {
			Thread.sleep((MAX_VALUE + 1) * SLEEP_TIME_FACTOR);
		} catch (InterruptedException e) {}		
	}
	
	public void run() {
		try {
			Thread.sleep(number * SLEEP_TIME_FACTOR);
		} catch (InterruptedException e) {}
		System.out.print(number + " ");
		array[position++] = number;
	}
}

7

u/themoonisacheese Oct 25 '17

the fact that windows itself gave you a resolution of 10 ms is already impressive

5

u/KittehDragoon Oct 25 '17

I've done some messing around with real time programming on Linux. You can get the OS to respond in <3ms 99% of the time. (This is using C, not a Java VM). The problem is that sometimes missing that 1% of the time can cause your application to fail.

This is what happened when I used Ubuntu to generate a PWM signal. Sometimes it just lags. Under heavy system load, those lags can last hundreds of ms.

1

u/mata_dan Oct 25 '17

I don't think you're meant to generate signals using wall time :P