C# 记录填充LinkedList和数组所需的时间
这个控制台应用程序有点奇怪,但如果它能工作的话,也有点有趣。首先,我记录用4.000.000个元素和随机数填充C# 记录填充LinkedList和数组所需的时间,c#,arrays,sorting,linked-list,console-application,C#,Arrays,Sorting,Linked List,Console Application,这个控制台应用程序有点奇怪,但如果它能工作的话,也有点有趣。首先,我记录用4.000.000个元素和随机数填充LinkedList所需的时间。然后我在LinkedList中搜索100个随机元素。在此期间,我会写出填充和查找元素所需的时间 在那之后,我尝试再次做同样的事情,但是使用数组。首先填充它,然后查找100个随机元素。然后我对数组进行排序,以查看在未排序的数组中查找100个随机元素与排序的数组之间的差异。然后再次输入时间 问题是,在我填充了LinkedList并在LinkedList中找到元
LinkedList
所需的时间。然后我在LinkedList
中搜索100个随机元素。在此期间,我会写出填充和查找元素所需的时间
在那之后,我尝试再次做同样的事情,但是使用数组。首先填充它,然后查找100个随机元素。然后我对数组
进行排序,以查看在未排序的数组中查找100个随机元素与排序的数组
之间的差异。然后再次输入时间
问题是,在我填充了LinkedList
并在LinkedList
中找到元素之后,我开始用循环填充数组。我得到一个无限循环。我真的不知道ATM机出了什么问题
如果你想帮忙的话,我建议你复制我粘贴到这个问题中的代码,这样你就能理解程序所有部分的外观
代码:
publicstaticboolsokning(int[]a,int-b)
{
bool-sant=false;
Random rand=新的Random();
秒表手表FinDarray=新秒表();
Console.Write(“Letar efter tal:”);
watchFindArray.Start();
int-myint=0;
对于(int iii=0;iii
致以最诚挚的问候。您不是在一个无限循环中,问题在于它包含以下代码:
for (int ii = 0; ii < MAX; ii++)
{
array[ii] = rand2.Next();
if (array.Length % 1000000 == 0)
{
Console.Write("#");
}
}
当您执行array[ii]=rand2.Next()时
您没有更改数组的长度,只是将其一个单元格的值设置为rand2.Next()代码>
这将导致控制台.Write(#)编码>以在每次迭代中工作,并显著降低循环速度
要解决此问题,只需更改:
if (array.Length % 1000000 == 0)
致:
你不希望每次都在数组末尾添加新项,因为每次调整数组的大小都会重新分配数组,速度非常慢,但是你可以使用这个方法(你没有理由这样做)我认为你在搜索数组的例程中遇到了一个大问题。(sokning
)
只搜索100个元素的代码在哪里
似乎你正在搜索一个随机生成的数字,搜索次数达4000万次。仅仅修复控制台。写入(“#”)以在每百万点正确写入是不够的。我认为让你认为有一个无限循环的大延迟是在你的代码中,在一个由4000万个数字组成的数组中搜索4000万个随机生成的数字
当然,这不是很“响应”(同时考虑到您调用此方法两次)
publicstaticboolsokning(int[]a,int-b)
{
bool-sant=false;
Random rand=新的Random();
秒表手表FinDarray=新秒表();
const int MAX = 40000000;
int[] array = new int[MAX];
if (array.Length % 1000000 == 0)
if (ii % 1000000 == 0)
public static bool sokning(int[] a, int b)
{
bool sant = false;
Random rand = new Random();
Stopwatch watchFindArray = new Stopwatch();
Console.Write("Letar efter tal: ");
watchFindArray.Start();
int myint = 0;
// Search only 100 numbers like you do in the linked list
for (int iii = 0; iii < 100; iii++)
{
b = rand.Next();
Console.Write("#");
myint = Array.BinarySearch(a, b);
if (myint < 0)
{
sant = false;
}
else
{
sant = true;
}
}
watchFindArray.Stop();
if (sant == true)
{
Console.WriteLine("\nFann alla element efter " + watchFindArray.Elapsed.TotalSeconds + " sekunder.");
return true;
}
else
{
return false;
}
}