不使用 Array.Reverse() 反转数组 [英] Reverse an array without using Array.Reverse()
本文介绍了不使用 Array.Reverse() 反转数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在不使用 Array.Reverse()
方法的情况下反转数组(在 C# 中)?
How to reverse an array (in C#) without using Array.Reverse()
method?
例如
int[] arr = {1,3,4,9,8};
// some code here
Console.WriteLine(string.Join(",", arr));
应该导致
8,9,4,3,1
这是我的面试任务.
推荐答案
问题中要替换的代码是:
The code to be substituted in place of // some code here
in the question is:
for (int i = 0; i < arr.Length / 2; i++)
{
int tmp = arr[i];
arr[i] = arr[arr.Length - i - 1];
arr[arr.Length - i - 1] = tmp;
}
您应该只遍历数组的前半部分 (arr.Length/2
).如果您遍历整个数组 (arr.Length
),它将被反转两次,产生与开始之前相同的元素顺序.
You should iterate only through the first half of the array (arr.Length / 2
). If you iterate through the whole array (arr.Length
), it will be reversed twice, yielding the same element order as before it started.
这篇关于不使用 Array.Reverse() 反转数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文