April 15, 2013

Listing all Permutations: The Recursive Way

Here is a general algorithm for listing all permutations of an array recursively. The code is given in C++, but can easily be ported to any language:

#ifndef __PERMUTE__
#define __PERMUTE__

template <class T>
void swap( T *a, T *b )
{
    T c = *a;
    *a  = *b;
    *b  = c;
}

template <class T>
void permute( T *array, const unsigned& size, unsigned current )
{
    if ( current == size-1 )
    {
        // Do what you want with the current permutation
    }
    else
    {
        for ( unsigned i = current; i < size; ++i )
        {
            swap( array+current, array+i );
            permute( array, size, current+1 );
            swap( array+current, array+i );
        }
    }
}

#endif

No comments:

Post a Comment