[ 來源:
.Net教程 | 作者:
.Net教程 | 時間:
2008-2-22 |
去論壇]
-
-
早上想到另一個方法,可能更合適,昨天的方法會有邊界問題,比如2後面一定是跟1
新的方法如下
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164267.gif)
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164263.gif)
int[] NUMList=new int[20]...{1,2,3,4,5,6,7,8,9,10,.....20};
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164251.gif)
private Random random=new Random;
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164251.gif)
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164251.gif)
public void GetRandom(ref int[] nUMList)
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164267.gif)
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164263.gif)
...{
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164258.gif)
int index;
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164258.gif)
int chang;
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164258.gif)
for(int iCount=19;iCount>0;iCount--)
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164370.gif)
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164369.gif)
...{
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164258.gif)
index=random.Next(0,iCount);
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164258.gif)
chang=nUMList[index];
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164258.gif)
numList[index]=nUMList[iCount];
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164258.gif)
nUMList[iCount]=chang;
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164360.gif)
}
![](https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017011311164354.gif)
}
相當與對數組做隨機交換,時間長度為0(n)