Microsoft Office 2000/Visual Basic Programmer's Guide |
Sorting an array is an iterative process that requires a fairly sophisticated algorithm. An example of a common sorting algorithm, the QuickSort algorithm, appears in the QuickSortArray procedure in the modArrays module in VBA.mdb in the ODETools\V9\Samples\OPG\Samples\CH07 subfolder on the Office 2000 Developer CD-ROM.
A full explanation of the QuickSort algorithm is beyond the scope of this book. The QuickSort algorithm is explained in thorough detail in the Visual Basic Language Developer's Handbook by Ken Getz and Mike Gilbert (Sybex, 1990)—a good place to start if you're looking for more information about sorting arrays.
In brief, the QuickSort algorithm works by using a divide-and-sort strategy. It first finds the middle element in the array, then works its way from the rightmost element to the middle, and from the leftmost element to the middle, comparing elements on both sides of the middle value and swapping their values if necessary. Once this part of the sort is complete, the values on the right side are all greater than those on the left, but they're not necessarily in order. The procedure then looks at the values on the left side by using the same strategy—finding a middle value and swapping elements on both sides. It does this until all the elements on the left side have been sorted, and then it tackles the right side. The procedure calls itself recursively and continues executing until the entire array has been sorted.