洗牌算法
這個代碼很簡單,只有兩行代碼,但是卻可以實現這個功能:對於給定的 n 個元素,生成的那個排列,每一個元素都能等概率地出現在每一個位置。
換句話說,每一個位置都能等概率地放置每個元素。
代碼如下:
for(int i = n - 1; i >= 0 ; i – )
swap(arr[i], arr[rand(0, i)]) // rand(0, i) 生成 [0, i] 之間的隨機整數
睡眠排序
public class SleepSort {
public static void main(String[] args) {
int[] ints = {1,4,7,3,8,9,2,6,5};
SortThread[] sortThreads = new SortThread[ints.length];
for (int i = 0; i < sortThreads.length; i++) {
sortThreads[i] = new SortThread(ints[i]);
}
for (int i = 0; i < sortThreads.length; i++) {
sortThreads[i].start();
}
}
}
class SortThread extends Thread{
int ms = 0;
public SortThread(int ms){
this.ms = ms;
}
public void run(){
try {
sleep(ms*10+10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ms);
}
}
它原理是構造 n 個線程,它們和這 n 個數一一對應。
初始化後,線程們開始睡眠,等到對應的數那麼多個時間單位後各自醒來,然後輸出它對應的數。
這樣最小的數對應的線程最早醒來,這個數最早被輸出。
等所有線程都醒來,排序就結束了。
不要問時間複雜度,時間複雜度在這個排序上已經毫無意義!