Pushpa
Pushpa

Reputation: 458

How to print all the Permutations of array elements efficienctly with minimum code

We have an array, int array={1,2,3};
Display all the possible permutations which will be

{1,3,2} ,
{2,1,3} , 
{2,3,1} , 
{3,1,2} , 
{3,2,1} etc.


all n! possibilities.

I know both ways direct recursive and backtracking too.
Is there any better way to do the same ?
Thank You.

Upvotes: 0

Views: 108

Answers (1)

Gyapti Jain
Gyapti Jain

Reputation: 4106

You can use the methods described here.

You can modify his algo slightly for your need:

#include <stdio.h>


void print(const int *v, const int size)
{
  if (v != 0) {
    for (int i = 0; i < size; i++) {
      printf("%c", i ? ',':'{');
      printf("%d", v[i] );
    }
    printf("}\n");
  }
} // print


void permute(int *v, const int start, const int n)
{  
  if (start == n-1) {
    print(v, n);
  }
  else {
    for (int i = start; i < n; i++) {
      int tmp = v[i];

      v[i] = v[start];
      v[start] = tmp;
      permute(v, start+1, n);
      v[start] = v[i];
      v[i] = tmp;
    }
  }
}


int main(void)
{
  int v[] = {1, 2, 3};
  permute(v, 0, sizeof(v)/sizeof(int));
}

Live example here

As described in other answer, C++ stl library provides an implmentation of next_permutation. You can peep inside stl code and make necessary changes to port it to C code.

Upvotes: 1

Related Questions