C# (C sharp) next_permutation function

Following the algorithm on wikipedia, I created a next_permutation function for C#. You have my permission to use it for anything (such as work, personal, or school projects) unless, of course, you are being directly tested on creating such a function (such as a school quiz, test, or homework assignment) in which case you do not have my permission to use it in any way.

/*
 * Transitions perm to the next lexigraphical permutation and
 * returns true, unless it is the last permutation, in which case
 * it resets to the first permutation and returns false
 */

static public bool next_permutation(int[] perm)
{
    int n = perm.Length;
    int k = -1;
    for (int i = 1; i < n; i++)
        if (perm[i - 1] < perm[i])
            k = i - 1;
    if (k == -1)
    {
        for (int i = 0; i < n; i++)
            perm[i] = i;
        return false;
    }

    int l = k + 1;
    for (int i = l; i < n; i++)
        if (perm[k] < perm[i])
            l = i;

    int t = perm[k];
    perm[k] = perm[l];
    perm[l] = t;

    Array.Reverse(perm, k + 1, perm.Length - (k + 1));

    return true;
}

Leave a Comment