In .NET Framework, the Array class provides a static Reverse method for reserving the order of elements within an array, or you can write your own method. For example an array as below:
int[] myArray = new int[5] {5, 6, 7, 8, 9, 10, 11};
You can use the status Reverse method in Array class, as in code:
Array.Reverse(myArray);
or you can write your own reversal method:
public static void DoReversal(int[] theArray) { int tempHolder = 0; if (theArray.Length > 0) { for (int counter = 0; counter < (theArray.Length / 2); counter++) { tempHolder = theArray[counter]; theArray[counter] = theArray[theArray.Length - counter - 1]; theArray[theArray.Length - counter - 1] = tempHolder; } } else { return; } }
The benefit of the DoReversal method is that it is about twice as fast as the Array.Reverse method. In addition, you can tailor the DoReversal method to a specific situation. For example, the DoReversal method accepts a value type array (int), whereas the Array.Reverse method accepts only a reference type (System.Array). This means that a boxing operation will occur for the int value types. The DoReversal method removes any boxing operations.
Reversing the elements in an array is a fairly common routine. The algorithm in DoReversal method swaps elements in the array until it is fully reversed. The array is actually reversed inside of the for loop. The for loop counts from zero (the first element in the array) to a value equal to the array’s length divided by two:
for (int counter = 0; counter < (theArray.Length / 2); counter++)
Note that this is integer division, so if the array length is an odd number, any digits to the right of the decimal point are truncated. If the array length is five, the for loop counts from zero to two. It means when the array length is odd number, the middle element will not be touched at all. Inside of the loop are three lines of code:
tempHolder = theArray[counter]; theArray[counter] = theArray[theArray.Length - counter - 1]; theArray[theArray.Length - counter - 1] = tempHolder;
These three lines swap the first half of the array with the second half. As the for loop counts from zero, these three lines swap the first and last elements in the array. The loop increments the counter by one, allowing the second element and the next to last element to be swapped. This continues on until all elements in the array have been swapped.
Popularity: 2% [?]
RSS feed for comments on this post · TrackBack URI
Leave a reply