- //数组的随机排序,也就是把一个数组的元素顺序打乱,例如洗牌。
- public static T[] RandomSort<T>(T[] array)
- {
- int len = array.Length;
- System.Collections.Generic.List<int> list = new System.Collections.Generic.List<int>();
- T[] ret=new T[len];
- Random rand = new Random();
- int i = 0;
- while (list.Count < len)
- {
- int iter = rand.Next(0, len);
- if (!list.Contains(iter))
- {
- list.Add(iter);
- ret[i] = array[iter];
- i++;
- }
- }
- return ret;
- }
- //调用
- static void Main()
- {
- string [] aaa = { "3", "1", "7", "5", "4", "2", "6" };
- string [] bbb = RandomSort(aaa);
- for (int i = 0; i < 7; i++) Console.WriteLine(bbb[i]);
- Console.ReadLine();
- }
数组随机排序
最新推荐文章于 2022-04-17 18:08:24 发布