第一种:
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,差不多。