C++: Sorting 2, 3 or 4 Values

The STL sort algorithm is very useful because it works both on STL containers and on normal arrays. It is hard to beat on performance too.

#include <algorithm>
int v[4] = { 99, 10, 5, 56 };
std::sort( v, v + 4 );

However, if your application needs to only sort 2, 3 or 4 length arrays whose values are simple types, you are better off using your own special sorting function written for these cases. Such scenarios occur in geometry, where you might be using a line segment (2 points), triangle (3 points) or a tetrahedron (4 points).

If you are processing millions of these objects, your application is significantly faster using a custom sort than the STL sort or a handwritten bubble sort. On a test with 20 million 4-length arrays, STL sort was 1.0s, bubble sort was 0.7s and custom sort was 0.5s.

void sort2( int* v )
{
    if ( v[0] > v[1] )
        swap( v[0], v[1] );

    return;
}

void sort3( int* v )
{
    if ( v[0] > v[1] )  swap( v[0], v[1] );
    if ( v[0] > v[2] )  swap( v[0], v[2] );
    if ( v[1] > v[2] )  swap( v[1], v[2] );

    return;
}

void sort4( int* v )
{
    if ( v[0] > v[1] )  swap( v[0], v[1] );
    if ( v[0] > v[2] )  swap( v[0], v[2] );
    if ( v[0] > v[3] )  swap( v[0], v[3] );

    sort3( &v[1] );

    return;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.