这几天做程序用到了数组排序,最后找到个这个简单的方法。(程序用C#实现)
有的时候需要对数组的成员打乱顺序,这样可以随机读取数组成员,达到固定数目随机读取的目的。
函数:
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;
}
调用:
string[] AA=new string[10];
AA[0] = "1";
AA[1] = "4";
AA[2] = "5";
AA[3] = "6";
AA[4] = "7";
AA[5] = "8";
AA[6] = "9";
AA[7] = "10";
AA[8] = "11";
AA[9] = "12";
string[] BB=RandomSort(AA);
所得到的BB就是新的顺序的数组。
我们可以用一些方便把数组成员显示出来。
例如:加一个label: this.label1.Text=BB[0]+BB[1]+BB[2]+ ...... 等等
这样就简单实现了打乱顺序。可用于,抽奖,抓阄,随机等程序中。
QQ:412437047