Thursday, May 3, 2012

C program for printing all permutations

#include <stdio.h>
void swap(int* a,int i,int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
}

void print_array(int* a,int n) {
        int i;
        for(i = 0; i<= n; ++i) {
                printf("%d ",a[i]);
        }
        printf("\n");
}

void permute(int* a, int i, int n) {
        int j;
        if(i == n) print_array(a,n);
        else {
                for(j = i;j <= n; j++) {
                        swap(a,i,j);
                        permute(a,i+1,n);
                        swap(a,i,j);
                }
        }
}

void main() {
        int a[4] = {1,2,3,4};
        permute(a,0,3);
}

No comments:

Blog Archive