C code for permutation

Programming Geeks : Permutation program


Finding all the permutations for any given set of items has always been an area of interest for programmers. A very simple algorithm for finding all the permutations, the
Bell Algorithm has already been presented.
Here the C code implementing Bell algorithm, for finding all the possible permutations has been given. The program assumes that the input set given will consist of integers. If however the input set contains characters, then the array definition should be changed to char and in the display funtion %d should be replaced by %c.

The executable file for this program can be downloaded from here : PERMUTE

#include<stdio.h>

void swap(int *,int*);
void permute(void);
int noofpermutations();
void display(void);

int m,n,noofterms,count=0;
int a[100];

void swap(int *p1,int *p2)
{   int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}

int noofpermutations()
{   int permutations=1,x;
for(x=1;x<=noofterms;x++)
permutations=permutations*x;
return permutations;
}

void display()
{   int x;
for(x=0;x<noofterms;x++)
printf(“%d  ”,a[x]);
printf(“\n”);
count++;
}

void permute()
{   int x,y;
while(count<noofpermutations())
{   for(y=0;y<noofterms-1;y++)
{  swap(&a[y],&a[y+1]);
display();
}
swap(&a[0],&a[1]);
display();
for(y=noofterms-1;y>0;y–)
{  swap(&a[y],&a[y-1]);
display();
}
swap(&a[noofterms-1],&a[noofterms-2]);
display();
}
}

main()
{   int x;
printf(“Enter no. of terms : “);
scanf(“%d”,&noofterms);
printf(“Enter the terms : “);
for(x=0;x<noofterms;x++)
scanf(“%d”,&a[x]);
printf(“\nPermutations are : \n”);
permute();
printf(“\nTotal Permutations : %d”,noofpermutations());
return 0;
}


Related Posts

Share

Filed Under: CCodes

About the Author: Software Engineer - Advanced Search & Recommendation at Rovi

RSSComments (3)

Leave a Reply | Trackback URL

  1. Ank says:

    This is intelligent use of call by value.
    My question is what if the inputs are not all different. Can anyone suggest how to remove duplicate outputs.

    • Saurabh says:

      Hi Ank,
      For the case when all the inputs are not different, you can first remove the duplicate elements are then use this code for displaying all the permutations.

  2. Ank says:

    if inputs are not all different, there will be duplicate outputs. anysuggestions on how to remove that.

Leave a Reply

*

AWSOM Powered