
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Reversing an Array Quickly
|
285
This code displays the following:
Element 0 = 1 ← The original array
Element 1 = 2
Element 2 = 3
Element 3 = 4
Element 4 = 5
Element 0 = 5 ← The reversed array
Element 1 = 4
Element 2 = 3
Element 3 = 2
Element 4 = 1
Reversing the elements in an array is a fairly common routine. The algorithm here
swaps elements in the array until it is fully reversed. The
DoReversal<T> method
accepts a single parameter,
theArray, which is a pointer to the first element in the
array that is to be 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, the remain-
der is discarded. Since your array length is five, the
for loop counts from zero to one.
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 ...