Title | Make a sorted collection class |
Keywords | sorting, algorithms, sorted collection class, SortedCollection class |
Categories | Algorithms |
|
|
See the book Ready-to-Run Visual Basic Algorithms
for more information on this and other sorting algorithms.
This class stores items in a normal collection. It inserts items in their proper places in the collection.
|
|
' Add an item at its correct position.
Public Sub AddItem(ByVal new_item As String)
Dim i As Integer
' See where the item belongs.
For i = 1 To m_Items.Count
If m_Items(i) >= new_item Then Exit For
Next i
' Insert the item.
If i > m_Items.Count Then
' Add at the end.
m_Items.Add new_item
Else
' Add at the right position.
m_Items.Add new_item, , i
End If
End Sub
|
|
The main reason the class stores items in a collection rather than an array, linked list, or
some other data structures is to provide the For Each operator. To do that, the class must
provide a NewEnum function that returns an IUnknown interface object. The class can get such
an object from a normal collection like this:
|
|
Public Function NewEnum() As IUnknown
Set NewEnum = m_Items.[_NewEnum]
End Function
|
|
To register this function as the class enumerator, you must:
- Open the SortedCollection's class editor window.
- Select the Tools menu's Procedure Attributes command.
- Select NewEnum in the Name box.
- Click Advanced >>
- Click on the Procedure ID box and type -4.
- Check the "Hide this member" box so the user cannot see this method
(it's really only useful indirectly via For each).
- Click Ok.
The Count, Remove, and Item methods are simply delegated to the m_Items collection.
|
|
' Return the number of items.
Public Function Count() As Integer
Count = m_Items.Count
End Function
' Remove an item.
Public Sub Remove(ByVal Index As Integer)
m_Items.Remove Index
End Sub
' Return an item.
Public Function Item(ByVal Index As Integer) As String
Item = m_Items(Index)
End Function
|
|
The class makes its Item method its default method. That allows a program using it to refer to items as in:
sorted_collection(K)
in addition to:
sorted_collection.Item(K)
To make Item be the default method, you must:
- Open the SortedCollection's class editor window.
- Select the Tools menu's Procedure Attributes command.
- Select Item in the Name box.
- Click Advanced >>
- Select (Default) in the Procedure ID box.
- Click Ok.
|
|
|
|