CodeItBetter Programming Another VB Programming Blog

How to sort an array

Posted on August 20, 2011
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
'Sorting - How to sort an array
'Sorting is an operation that you often perform on arrays. As you probably know,
'there are dozens of different sort algorithms, each one with its strengths and
'weaknesses. I found that the Shell Sort algorithm works well in most cases, and
'I 've prepared a generic routine that sorts any one-dimensional array of a data
'type compatible with the Variant type, either in ascending or descending order:

Public Sub ShellSortAny(arr As Variant, numEls As Long, descending As Boolean)
    Dim index As Long, index2 As Long, firstItem As Long
    Dim distance As Long, value As Variant
    ' Exit if it is not an array.
    If VarType(arr) < vbArray Then Exit Sub
    firstItem = LBound(arr)
    ' Find the best value for distance.
    Do
        distance = distance * 3 + 1
    Loop Until distance > numEls
    ' Sort the array.
    Do
        distance = distance \ 3
        For index = distance + firstItem To numEls + firstItem - 1
            value = arr(index)
            index2 = index
            Do While (arr(index2 - distance) > value) Xor descending
                arr(index2) = arr(index2 - distance)
                index2 = index2 - distance
                If index2 - distance < firstItem Then Exit Do
            Loop
            arr(index2) = value
        Next
    Loop Until distance = 1
End Sub
Filed under: Sorting Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.