#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void reverse(int *array, const int start, const int length)
{
int i;
for (i = 0; i < length / 2; i++)
swap(&array[start + i], &array[start + length - i - 1]);
}
void reverseAfter(int *array, const int size, const int index)
{
reverse(array, index + 1, size - index - 1);
}
void printArray(int *array, const int size)
{
int i;
for (i = 0; i < size; i++)
{
printf("%d", array[i]);
if (i + 1 == size)
putchar('\n');
else
printf(", ");
}
}
int nextArrangement(int *array, const int size)
{
int i = size - 1;
int j, min, minIndex;
int flag = 0;
while (i--)
{
if (array[i] < array[i + 1])
{
flag = 1;
break;
}
}
if (flag == 0)
return 0; // already the last arrangement
min = array[i + 1];
minIndex = i + 1;
for (j = i + 2; j < size; j++)
{
if (array[j] < min && array[j] > array[i])
{
flag = 1;
min = array[j];
minIndex = j;
}
}
swap(&array[i], &array[minIndex]);
reverseAfter(array, size, i);
return 1;
}
int *cloneArray(const int *array, int size)
{
size *= sizeof(int);
int *pArray = (int *)malloc(size);
memcpy(pArray, array, size);
return pArray;
}
void showAllArrangements(const int *array, const int size)
{
int *p1 = cloneArray(array, size);
do
{
printArray(p1, size);
} while (nextArrangement(p1, size));
free(p1);
}
int main(int argc, char *argv[])
{
int list[] = {1, 2, 3, 4, 5};
showAllArrangements(list, sizeof(list) / sizeof(int));
return 0;
}