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.

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as