Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Sorting 2, 3 or 4 Values

📅 2010-Dec-17 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, sorting ⬩ 📚 Archive

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;
}