Library tutorials & articles

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.

Comments

  1. 01 Jan 1999 at 00:00

    This thread is for discussions of A guide to sorting.

Leave a comment

Sign in or Join us (it's free).

Joseph M. Newcomer

Want to stay in touch with what's going on? Follow us on twitter!