|
|
|
Frequently you need to sort arrays of records using multiple keys. This may be required since one single key does not uniquely identify a record (e.g. you may need both LastName and FirstName to select a given employee in a large company where people with same name work), or it may be necessary for reporting chores (for instance, you might sort the list of employees on their department first, and then on their name: the neat result is a list of employees grouped by their department and sorted alphabetically within each group).
If you need to sort on multiple keys you may follow different approaches. When all the keys that are involved are of string type, you may concatenate them to form a single key, then indirectly sort the array on that compound key. This approach works correctly only when working with fixed-length strings, otherwise it is up to you to make all string keys of same length. In the next example I'll show how an array of employees data can be sorted on the compound key "dept + name": |
Click here to copy the following block | Type TEmployees name As String * 40 dept As String * 12 salary As Currency End Type
ReDim employees(1 To 1) As TEmployees Open "employees.dat" For Binary As #1 numEls = LOF(1) / Len(employees(1)) ReDim employees(1 To numEls) As TEmployees Get #1, , employees() Close #1
ReDim keys(1 To numEls) As String For index = 1 To numEls keys(index) = employees(index).dept & employees(index).name Next
ReDim ndx(1 To numEls) As Long NdxShellSort keys(), ndx(), , True
dept = "" For index = 1 To numEls With employees(ndx(index)) If .dept <> dept Then dept = .dept Debug.Print "Dept: " & dept End If Debug.Print .name, .salary End With Next |
Unfortunately, this simple method does not work when the compound key includes non-string (numerical) data. For instance, say we wish to sort on the key "dept + salary" the concatenation operation will not yield a useful string for our sorting purposes. However, we can still use this method by properly formatting the numerical data before building the compound key: |
The Format$ functions correctly align the numerical information so that it can be compared as it was a string. This methods works also with Integer and Long values, and even Single and Double data, but you must carefully choose the mask argument in the Format$ function so that no overflow error occurs. |
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|