SoFunction
Updated on 2025-03-07

Detailed explanation of three C# methods to implement array inversion

After eating at noon at work today, I saw a question on the blog: Array Reversal. I had nothing to do after taking a shower at night, so I practiced myself.

public static class ArrayReserve 
  { 
    /// <summary> 
    /// Use (Arrar) to reverse all    /// </summary> 
    /// <param name="arr"></param> 
    public static void ReverseDemo1(int[] arr) 
    { 
      ("use (Arrar) Reverse all"); 
      (arr); 
    } 
    /// <summary> 
    /// Use (Array arr,int begin,int end), reverse the specified part    /// </summary> 
    /// <param name="arr"></param> 
    /// <param name="begin"></param> 
    /// <param name="end"></param> 
    public static void ReverseDemo2(int[] arr, int begin, int end) 
    { 
      ("use (Array arr,int begin,int end),Reverse the specified part"); 
      (arr, begin, end); 
    } 
    /// <summary> 
    /// Use custom methods to achieve inversion    /// </summary> 
    /// <param name="arr"></param> 
    /// <param name="begin"></param> 
    /// <param name="end"></param> 
    public static void ReverseDemo3(int[] arr, int begin, int end) 
    { 
      ("Use custom methods to achieve inversion"); 
      if(null==arr) 
      { 
        throw new ArgumentNullException("arr", "Array cannot be null"); 
      } 
      if(begin<=0 || end <=0) 
      { 
        throw new ArgumentOutOfRangeException("The start or end index is not set correctly"); 
      } 
      if(end>) 
      { 
        throw new ArgumentOutOfRangeException("end", "End index exceeds array length"); 
      } 
      while(begin<end) 
      { 
        int temp = arr[end]; 
        arr[end] = arr[begin]; 
        arr[begin] = temp; 
        begin++; 
        end--; 
      } 
    } 
  /// <summary> 
    /// Use custom methods to achieve inversion (using stack "Last In First Out")    /// </summary> 
    /// <param name="arr"></param> 
    /// <param name="begin"></param> 
    /// <param name="end"></param> 
    public static void ReverseDemo4(int[] arr, int begin, int end) 
    { 
      ("use自定义方法实现反转(use栈《Later in and first out》)"); 
      if (null == arr) 
      { 
        throw new ArgumentNullException("arr", "Array cannot be null"); 
      } 
      if (begin <= 0 || end <= 0) 
      { 
        throw new ArgumentOutOfRangeException("The start or end index is not set correctly"); 
      } 
      if (end > ) 
      { 
        throw new ArgumentOutOfRangeException("end", "End index exceeds array length"); 
      } 
      Stack<int> intStack = new Stack<int>(); 
      int tempBegin = begin; 
      for(;begin<=end;begin++) 
      { 
        (arr[begin]); 
      } 
      for (; tempBegin <= end; tempBegin++) 
      { 
        arr[tempBegin] = (); 
      } 
    } 
  }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.