Array.Reverse 內建可用,但理解原地反轉演算法是面試與教學經典。using System;
using System.Diagnostics;
public static class ArrayExtensions
{
public static void ReverseInPlace<T>(this T[] array)
{
if (array == null)
throw new ArgumentNullException(nameof(array), "陣列不可為 null");
if (array.Length <= 1) return; // 0 或 1 元素無需反轉
for (int i = 0, j = array.Length - 1; i < j; i++, j--)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
int[] nums = { 1, 2, 3, 4, 5 };
nums.ReverseInPlace();
// nums 現在為 { 5, 4, 3, 2, 1 }
string[] words = { "a", "b", "c" };
words.ReverseInPlace();
// words 現在為 { "c", "b", "a" }
| 指標 | 數值 | 說明 |
|---|---|---|
| 時間複雜度 | O(n) | 單一迴圈,n/2 次交換 |
| 空間複雜度 | O(1) | 僅使用一個暫存變數 temp |
| 穩定性 | 不穩定 | 相等元素相對位置會改變 |
| 原地操作 | 是 | 直接修改原陣列,不配置新陣列 |
int[] empty = { };
empty.ReverseInPlace(); // 正常返回,無例外
int[] single = { 42 };
single.ReverseInPlace(); // 正常返回
int[] nullArr = null;
try { nullArr.ReverseInPlace(); }
catch (ArgumentNullException ex) { Console.WriteLine(ex.Message); }
雙指針向中間交換,是陣列反轉的標準解法。實務上請直接呼叫 Array.Reverse(array) 或 list.Reverse(),框架實作經過高度優化且通過測試;理解演算法邏輯則有助於面試與底層除錯。