Skip to content

Instantly share code, notes, and snippets.

@ashelly
Created February 1, 2019 04:59

Revisions

  1. ashelly created this gist Feb 1, 2019.
    18 changes: 18 additions & 0 deletions permutation.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    static inline void Exchange(int* data, int a, int b) {
    int temp = data[a];
    data[a]=data[b];
    data[b]=temp;
    }

    //generates all permutations of initially sorted array `a` with `n` elements
    //returns 0 when no more permutations exist
    int genPermutation(int a[], int n)
    {
    int l,j;
    for (j = --n; j > 0 && a[j-1] >= a[j]; --j) { ; }
    if (j == 0) return 0;
    for (l = n; a[j-1] >= a[l]; --l) { ; }
    Exchange(a, j-1, l);
    while (j < n) { Exchange(a, j++ ,n--); }
    return 1;
    }