public class SleepSort {
public static int counter = 0;
public static int sortedArr[];
public static int arr[] = {21,12,14,1,26,34,67,45,0};
public static int threadCount=0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("printing unsorted array");
printArray(arr);
sortedArr = new int[arr.length];
for(int i=0;i<arr.length;i++){
SleepThread t = new SleepThread(arr[i],i);
t.start();
threadCount++;
}
}
public static void printArray(int arr[]){
for(int k=0;k<arr.length;k++)
System.out.print(arr[k]+" ");
System.out.println("");
}
}
class SleepThread extends Thread{
int multiple,position;
public SleepThread(int multiple, int position){
this.multiple=multiple;
this.position=position;
}
public void run(){
try {
sleep(1000*this.multiple);
SleepSort.sortedArr[SleepSort.counter++] = SleepSort.arr[this.position];
SleepSort.threadCount--;
System.out.println("sorted array after value "+multiple+", position ::"+this.position);
SleepSort.printArray(SleepSort.sortedArr);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output :
printing unsorted array 21 12 14 1 26 34 67 45 0 sorted array after value 0, position ::8 0 0 0 0 0 0 0 0 0 sorted array after value 1, position ::3 0 1 0 0 0 0 0 0 0 sorted array after value 12, position ::1 0 1 12 0 0 0 0 0 0 sorted array after value 14, position ::2 0 1 12 14 0 0 0 0 0 sorted array after value 21, position ::0 0 1 12 14 21 0 0 0 0 sorted array after value 26, position ::4 0 1 12 14 21 26 0 0 0 sorted array after value 34, position ::5 0 1 12 14 21 26 34 0 0 sorted array after value 45, position ::7 0 1 12 14 21 26 34 45 0 sorted array after value 67, position ::6 0 1 12 14 21 26 34 45 67