A guide to sorting

Multifield Sorting

Suppose I want to sort the data so that it is numeric my year, and within year, alphabetic by name. This is not terribly hard. You first sort by the main key, and then by the subkey.

int bynameinyear(const void * v1, const void * v2)
{
    pmyData data1 = *(pmyData *)v1;
    pmyData data2 = *(pmyData *)v2;
    int dt = (int)data1->birthday - (int)data2->birthday;
    if(dt != 0)
        return dt;
    // same year
    return _tcscmp(data1->name, data2->name);
}

Note that this first checks to see if the years differ, If the years differ, the decision is already made. If the years are the same, we then need to compare the two values of the names. We can apply this repeatedly; each time we find an equal field, we compare the next subkey of the sort. So we could do alphabetic by state, within state by city, within city by streetname, within streetname by house number, and so on.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“My definition of an expert in any field is a person who knows enough about what's really going on to be scared.” - P. J. Plauger