To reverse an array in C#, you can either create a new array with reversed elements or you can reverse the elements in place, without creating a new array.
For in-place array reversal, you can use the following algorithm:
main.cs346 chars18 lines
Here, we initialize two pointers, start
and end
, at the beginning and end of the array respectively. Then, we swap the elements at these positions and move both pointers towards the center of the array until they meet in the middle.
To reverse an array in C# using a new array, you can use the Array.Reverse
method:
main.cs177 chars11 lines
Here, we create a copy of the original array using the Clone
method, and then we call the Reverse
method of the Array
class to reverse the elements. Finally, we print out the reversed elements using a foreach
loop. Note that the original array is not modified by this operation.
gistlibby LogSnag