我为什么需要乱序排序:
我想实现“刷”网站的效果。
思路:
底层的思路是桶排序(我认为最好理解的排序方式),
获取总共要排序的数量,将对象集合的下标乱序排序。
在取值时,直接取对象集合对应的下标。实现乱序。
代码:
//乱序排序的总数
int count = 10;
//声明数组
int[] arr = new int[count];
//遍历存储数组下标
for (int j = 0; j < count; j++)
{
arr[j] = j;
}
//声明乱序的数组
int[] arr2 = new int[count];
int i = 0;// 索引
int index;// 随机位置
do
{
Random rand = new Random();
int r = count - i; //随机数取值范围
index = rand.Next(r); //产生的随机数
arr2[i++] = arr[index]; //依次将随机的位置数字填充到新数组中
arr[index] = arr[r - 1];// 将最后一位数值赋值给已经被使用的index
} while (i < count);
//遍历输出乱序排序后的结果
foreach (var item in arr2)
{
Console.Write(item + " ");
}