第一种:
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
int[] a = new int[1000];
for (int index = 0; index < 1000; index++)
{
a[index] = index;
}
int tmp = 0;
for (int j = 0; j < a.Length / 2; ++j) {
tmp = a[j];
a[j] = a[a.Length -1 - j];
a[a.Length-1 - j] = tmp;
}
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
}
为了测试,初始化的时候用循环赋值的。这段代码用到的命名空间System.Diagnostics;
执行时间:350ms
第二种:
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
int[] a = new int[1000];
for (int index = 0; index < 1000; index++)
{
a[index] = index;
}
Array.Reverse(a);
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
}
这个我是直接用C#Array.Reverse倒置,执行的时间为366ms,差不多。
本文通过两种不同的方法实现C#中数组的反转,并对比了它们的执行效率。第一种方法使用循环交换元素的方式手动反转数组,而第二种方法则利用了C#内置的Array.Reverse()函数。测试结果显示两者执行时间相近,分别为350ms和366ms。
213

被折叠的 条评论
为什么被折叠?



