2011-01-30 64 views
2

我想出什麼樣的主意是:給定一個字符串數組什麼是隨機排序他們最簡單的方法是什麼?

RandomSort() 
{ 
    string[] list = { "Alpha", "Beta", "Gamma", ... } 
    Random rnd = new Random(); 
    string[] list2 = list.OrderBy((x) => rnd.NextDouble()).ToArray(); 
} 

有一些其他的方式,也許用Dictionary什麼?謝謝。

+3

[This question](http://stackoverflow.com/q/108819/128397)的完全重複,其中最佳答案實際上不是接受的答案,而是[this one](http://stackoverflow.com/問題/ 108819/best-way-to-randomize-a-string-array-in-c/110570#110570),它具有用於Fisher-Yates Shuffle又名Knuth Shuffle實現的C#代碼。 – 2011-01-30 01:11:54

回答

6

這當然很簡單,但它是O(n log(n))。通過使用Fisher Yates洗牌,您可以更好地實現性能。

相關問題