i found this code on the net a while ago. it was originally in c++ but i changed it to c because i had never messed with c++ before. i also added a sort function and a main driver so i could play with it a bit. i finally had to sit down with paper and pencil to understand how it worked (probably because im slow). anyway, hope it helps.
Code:
#include <stdio.h>
#include <string.h>
typedef enum { FALSE, TRUE } BOOL;
void swap(char *a, char *b)
{
char t = *a;
*a = *b; *b = t;
}
void rev(char *begin, char *end)
{
if(*end == '\0') end--;
while(begin < end)
{ swap(begin, end); begin++; end--; }
}
BOOL NextPerm(char *first, char *last)
{
char *a, *b, *c;
if(first == last) return FALSE;
a = first; a++;
if(a == last) return FALSE;
a = last; a--;
for(;/*ever*/;)
{
b = a--;
if(*a < *b)
{
c = last;
while(!(*a < *--c));
swap(a, c); rev(b, last);
return TRUE;
}
if(a == first)
{ rev(first, last); return FALSE; }
}
}
void InsertionSort(char *a, int l, int r)
{
char v;
int i, j;
for(i = l + 1; i <= r; i++)
{
j = i - 1; v = a[i];
while(j >= l && (v < a[j]))
{ a[j+1] = a[j]; j--; }
a[j+1] = v;
}
}
int main(int argc, char *argv[])
{
char *begin, *end;
int col = 0;
if(argc < 2)
{ printf("usage: perm <arg>\n"); return 0; }
InsertionSort(argv[1], 0, strlen(argv[1]) - 1);
while(NextPerm(argv[1], argv[1] + strlen(argv[1])))
{
if(col++ % 3 == 0) printf("\n");
printf("%-15s", argv[1]);
}
printf("%-15s\n", argv[1]);
return 0;
}
btw, i realize other people have already offered solutions, but i thought you might be interested.