}
private int[] RandomSort(int[] arr)
{
SortedList sl=new SortedList();
Random rad=new Random();
foreach(int i in arr)
{
int ikey;
do
{
ikey=rad.Next(1000000000);
}while(sl.ContainsKey(ikey));
sl.Add(ikey,i);
}
int count=0;
foreach(object o in sl.Keys)
{
arr[count]=int.Parse(sl[o].ToString());
count++;
}
return arr;
}
20000条生成速度是0.5秒,应该满足要求
经过分布统计确定,1-200在各位置上出现的概率是平均分布
public static int GetRandomSeed()
{
byte[] rndBytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(rndBytes);
return BitConverter.ToInt32(rndBytes,0);
}
public static int[] GetRandomSort(int[] arr)
{
int k = arr.Length; // 要保存的位置
Random rad=new Random(GetRandomSeed());
for( int i = 0; i < k-1; i++ ) // 执行N-1次循环,随机产生要被打乱的数据所在的位置
{
int idx = rad.Next(0,k-i);
// 交换数据
int n = arr[idx];
arr[idx] = arr[k-i-1];
arr[k-i-1] = n;
}
return arr;
}
MSN:liangpz_2000@hotmail.com QQ:18692679
private void button2_Click(object sender, System.EventArgs e)
{
arrInt = InitArray(1,100000);
arrInt = RandomSort(arrInt);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for( int i = 0; i < arrInt.Length-1; i++ )
{
sb.Append(arrInt[i].ToString() + "\r\n");
}
textBox1.Text = sb.ToString();
sb = null;
}
public int[] RandomSort(int[] arr)
{
int k = arr.Length-1; // 要保存的位置
Random rad=new Random();
for( int i = 0; i < arr.Length-1; i++ ) // 执行N-1次循环,随机产生要被打乱的数据所在的位置
{
int idx = rad.Next(0,k+1);
// 交换数据
int n = arr[idx];
arr[idx] = arr[k-1];
arr[k-1] = n;
// 递减要保存的位置
k--;
}
return arr;
}
int[] arrInt = null;
private int[] InitArray(int min, int max)
{
arrInt = new int[max - min];
for(int i = min; i < max; i++)
{
arrInt[i-min] = i;
}
return arrInt;
}
我用了一百万,速度也很快。
using System;
public class Test
{
public static int [] Random(int n)
{
int [] a = new int[n];
for(int i = 0; i < n; i++) a[i] = i;
Random r = new Random();
for(int i = 0; i < n; i++)
{
int m = a[i];
int k = i + r.Next() % (n - i);
a[i] = a[k];
a[k] = m;
}
return a;
}
public static void Main(string[] args)
{
foreach(int n in Random(20)) Console.WriteLine(n);
}
}