4

I have the following program for finding all possible permutations of a string.

#include <stdio.h>

 /* Function to swap values at two pointers */
 void swap (char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int i, int n)
{
   int j;
   if (i == n)
       printf("%s\n", a);
   else
   {
       for (j = i; j <= n; j++)
       {
          swap((a+i), (a+j));
          permute(a, i+1, n);
          swap((a+i), (a+j)); //backtrack
       }
   }
}

/* Driver program to test above functions */
int main()
{
   char a[] = "abcd";
   permute(a, 0, 3);
   getchar();
   return 0;
}

I need to know is there any better way(efficient) to find all permutations because this algorithm is having O(n^n) efficiency.

Thank you.. :-)

Gokul
  • 3,101
  • 4
  • 27
  • 45
  • 3
    Why don't you use `std::next_permutation`? – Mohit Jain Apr 13 '15 at 11:50
  • 3
    I assume you're using C, not C++ (despite your extra tagging) otherwise you could just use [`std::next_permutation`](http://en.cppreference.com/w/cpp/algorithm/next_permutation) from `` – Cory Kramer Apr 13 '15 at 11:50
  • If you are actually using C and not C++ you can adapt the code [here](http://stackoverflow.com/questions/11483060/stdnext-permutation-implementation-explanation) into C code. The post is how you would implement a next_permutation function. – NathanOliver Apr 13 '15 at 12:06

2 Answers2

6

It is there in standard

#include<algorithm>
std::vector<int> vec;
std::next_permutation(std::begin(vec), std::end(vec));

In case of string

# include<string>
#include<algorithm>

std::string str ="abcd"
do{
     std::cout<<str<<"\n";

} while(std::next_permutation(std::begin(str), std::end(str)));
Steephen
  • 14,645
  • 7
  • 40
  • 47
1

There is no faster algorithm than O(n * n!) as you have to enumerate all the n! possibilities, and you have n characters to process each time.

Your algoirthm also runs in O(n* n!) complexity, as it can be seen in http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/

  • 3
    You can't beat O(n * n!) if you want to actually *output* each permutation, but you can in fact generate them faster, using just a single swap to generate the next permutation from the current one: https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm. With Even's speedup, this takes just O(n!) overall. – j_random_hacker Apr 13 '15 at 12:32