| Re-ordering data numerically, chronologically or alphabetically
is a simple task for data held in tables or grids as these object have
inherent sorting methods. However data held in arrays can present a
problem requiring a manually coded solution. Consider the data below held
in an array.
|
Age
|
Height
|
|
35
|
140
|
|
28
|
170
|
|
25
|
165
|
|
21
|
180
|
|
28
|
155
|
The traditional method would be to perform a bubble sort where the
contents are compared in progressive pairs until all the data has been
traverse then the process is repeated n times, where n is
the number of elements in the array. The array in the code below is a user defined
type array, containing two integers Age and Height for clarify of example:
For intOuterLoop = 1 to 5
For intInnerLoop = 1 to 4
If array(intInnerLoop).Age > array(intInnerLoop + 1).Age Then
'swap elements intInnerLoop and intInnerLoop + 1 around
End If
Next intInnerLoop
Next intOuterLoop
The theory behind this approach is borne out statistically, because if
all the elements are in reverse order then n passes of swapping
pairs are required to ensure ordered data, as the corrected pairs
gradually shift the data to their appropriate position. However this worse case
scenario approach can introduce unnecessary overheads. If, for example,
only a pair of elements in a very large array are out of order then
iterating through all that data so many times may be statistically sound,
but in reality complete overkill.
The most efficient approach is to use a flag representing the success
of a traverse through all the element and a loop based upon the state of
such a flag, as follows:
blnSuccess = False
Do While Not blnSuccess
blnSuccess = True
For intInnerLoop = 1 to 4
If array(intInnerLoop).Age > array(intInnerLoop + 1).Age Then
blnSuccess = False
'swap elements intInnerLoop and intInnerLoop + 1 around
End If
Next intInnerLoop
LoopThis method now only steps through the data until a successful order is
achieved, instead of a fixed, predetermined number.
|