Search code examples
c++algorithmpermutationheaps-algorithm

Implementing Heap's algorithm in C++


I am trying to implement Heap's algorithm in C++. I feel I have written the code exactly as the algorithm works but it is giving wrong results.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void print(vector<int> v)

{ 
   for(auto x:v) 
            cout<<x;
   cout<<endl;
}

void gen(vector<int> v,int n)

{  
      if(v.size()==1) 
          cout<<v[0];
      print(v);
      int i = 0;
      while(i<n)
       {
          gen(v,n-1);
          if(n%2) 
               swap(v[n-1],v[0]);
          else 
               swap(v[n-1],v[i]);
          i++;
       }

}


int main()
{
  vector<int>  v  ={1,2,3};
  gen(v,v.size());
}

I am stuck at trying to make this work. For the vector in the above code, it gives the absurd result:

123 123 123 123 213 213 321 321 321 231 231 123 123 123 213 213


Solution

  • The Wiki page shows an if-else that's missing from your code. The one if that you have does something completely different.

    Also, I'd add a std::endl after the cout, and try with the input 1 2 3 4. The linked article has a line-by-line example of the algorithm running for 4 elements.