devxlogo

Sorting on multiple keys

Sorting on multiple keys

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”:

Type TEmployees    name As String * 40    dept As String * 12    salary As CurrencyEnd Type' load the array from diskReDim employees(1 To 1) As TEmployeesOpen "employees.dat" For Binary As #1numEls = LOF(1) / Len(employees(1))ReDim employees(1 To numEls) As TEmployeesGet #1, , employees()Close #1' create a temporary array holding key dataReDim keys(1 To numEls) As StringFor index = 1 To numEls    keys(index) = employees(index).dept & employees(index).nameNext' perform the indexed sort in descending orderReDim ndx(1 To numEls) As LongNdxShellSort keys(), ndx(), , True' print the name of employees ' in each departmentdept = ""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:

' create a temporary array holding key dataReDim keys(1 To numEls) As StringFor index = 1 To numEls    keys(index) = employees(index).dept & Format$(employees(index).salary, _        "0000000.00")Next

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.

See also  Why ChatGPT Is So Important Today

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist