You are to trace out the execution of Heaps algorithm for ge
You are to trace out the execution of Heap’s algorithm for generating permutations of four elements. Since the “solution” is available on the web, a large part of getting full marks for this homework will be that you can explain and/or trace out the execution of the algorithm. For this, you might want to hack the 10 line program that will do this, using the pseudocode in the text or a different version of code. If you do that, be sure to include your code as part of your submission
Solution
**** ************Heap’s algorithm for generating permutations of four elements**********************
--calculate_permutations function have main logic for calculating permutations of number
--You have to pass two argument in calculate_permutationsone function one is arry with four element and second is size or length in this case length=4(because permutations of four numbers)
void calculate_permutations(int v[], int n) {
int i;
if (n == 1) {
print_permutations(v); // this function print the value
}
else {
for (i = 0; i < n; i++) {
calculate_permutations(v, n-1);
if (n % 2 == 1) {
swap(&v[0], &v[n-1]); //this function swap the variable
}
else {
swap(&v[i], &v[n-1]);
}
}
}
}
**************************************************Code**************************************************************
#include <stdio.h>
#include <stdlib.h>
int length;
void calculate_permutations(int v[], int n) {
int i;
if (n == 1) {
print_permutations(v);
}
else {
for (i = 0; i < n; i++) {
calculate_permutations(v, n-1);
if (n % 2 == 1) {
swap(&v[0], &v[n-1]);
}
else {
swap(&v[i], &v[n-1]);
}
}
}
}
void print_permutations(const int *v)
{
int i;
int size = length;
if (v != 0) {
for ( i = 0; i < size; i++) {
printf(\"%4d\", v[i] );
}
printf(\"\ \");
}
}
void swap (int *x, char *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int number[]={1,2,3,4};
length=4;
printf(\"permutations of four elements:\");
calculate_permutations(number, length);
return 0;
}

