This C program implements Heap’s Algorithm for Permutation of N numbers.

Heap’s algorithm is an algorithm used for generating all possible permutations of some given length. It was first proposed by B. R. Heap in 1963. It generates each permutation from the previous one by choosing a pair of elements to interchange.

Here is the source code of the C program to implement recursive version of Heap’s algorithm. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

`#include <stdio.h>`

`#include <stdlib.h>`

int len;

void swap (int *x, char *y)

`{`

int temp;

temp = *x;

*x = *y;

*y = temp;

`}`

void print(const int *v)

`{`

int i;

int size = len;

if (v != 0) {

for ( i = 0; i < size; i++) {

printf("%4d", v[i] );

`}`

printf("\n");

`}`

`}`

void heappermute(int v[], int n) {

int i;

if (n == 1) {

print(v);

`}`

else {

for (i = 0; i < n; i++) {

heappermute(v, n-1);

if (n % 2 == 1) {

swap(&v[0], &v[n-1]);

`}`

else {

swap(&v[i], &v[n-1]);

`}`

`}`

`}`

`}`

int main()

`{`

int num[11];

int i;

printf("How many numbers you want to enter: ", len);

scanf("%d", &len);

printf("\nEnter %d numbers: ");

for ( i = 0 ; i < len; i++)

scanf("%d", &num[i]);

heappermute(num, len);

return 0;

`}`

$ gcc heappermute.c -o heappermute $ ./heappermute How many numbers you want to enter: 4 Enter 4 numbers: 3 1 2 4 3 1 2 4 1 3 2 4 2 3 1 4 3 2 1 4 1 2 3 4 2 1 3 4 4 1 2 3 1 4 2 3 2 4 1 3 4 2 1 3 1 2 4 3 2 1 4 3 4 3 2 1 3 4 2 1 2 4 3 1 4 2 3 1 3 2 4 1 2 3 4 1 4 3 1 2 3 4 1 2 1 4 3 2 4 1 3 2 3 1 4 2 1 3 4 2

**Sanfoundry Global Education & Learning Series – 1000 C Programs.**

Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms.