日期:2014-05-18 浏览次数:21430 次
List<int> list = new List<int>();
while (list.Count != 100)
{
int i = new Random().Next(1,101);
if (!list.Contains(i))
{
list.Add(i);
}
}
------解决方案--------------------
//构造数组
int[] array = new int[100];
Random rand = new Random();
for (int i = 0; i < 100; i++)
{
array[i] = i + 1;
}
//随机打乱顺序
for (int i = 0; i < 100; i++)
{
int swapIndex = rand.Next(100);
int temp = array[i];
array[i] = array[swapIndex];
array[swapIndex] = temp;
}
//冒泡排序
for (int i = 0; i < 100; i++)
{
for (int j = i + 1; j < 100; j++)
{
if (array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
------解决方案--------------------
//这个是不是快些了
List<int> list = new List<int>(); //用于存放1-100有序的数
List<int> newList = new List<int>(); //用于存放随机出来1-100的数
for (int i = 0; i < 100; i++)
{
list.Add(i + 1); //循环添加有循的1-100的数
}
while (list.Count != 0)
{
int index = new Random().Next(0, list.Count); //随机出来的有序List的索引值
int flag = list[index]; //从有序List里随机出来的数
list.RemoveAt(index); //随机出来的数从有序List里移除
newList.Add(flag); //添加到新的List中
}
------解决方案--------------------
static void Main(string[] args)
{
List<int> list = new List<int>(); //用于存放1-100有序的数
List<int> newList = new List<int>(); //用于存放随机出来1-100的数
for (int i = 0; i < 100; i++)
{
list.Add(i + 1); //循环添加有循的1-100的数
}
while (list.Count != 0)
{
int index = new Random().Next(0, list.Count); //随机出来的有序List的索引值
int flag = list[index]; //从有序List里随机出来的数
list.RemoveAt(index); //随机出来的数从有序List里移除
newList.Add(flag); //添加到新的List中
}
//-----------------------下面是冒泡排序(排序的算法这个真要懂,请看看资料)--------------------------
int temp = 0;
for (int i = newList.Count; i > 0; i--)
{
for (int j = 0; j < i - 1; j++)
{
if (newList[j] > newList[j + 1])
{
temp = newList[j];
newList[j] = newList[j + 1];
newList[j + 1] = temp;
}
}
}
//-------------------------这里是冒泡排序之后再输出-----------------------
for (int i = 0; i < newList.Count; i++)
{
Console.WriteLine(newList[i]);
}
Console.ReadLine();
}