Skip to content

Instantly share code, notes, and snippets.

@bruceoutdoors
Forked from ishikawa/HeapPermute.java
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bruceoutdoors/4b7101edba65a5d77d99 to your computer and use it in GitHub Desktop.
Save bruceoutdoors/4b7101edba65a5d77d99 to your computer and use it in GitHub Desktop.
Heap's algorithm is an algorithm used for generating all possible permutations of some given length.
#include <iostream>
using namespace std;
const int SIZE = 4;
void printArray(int arr[], int size)
{
for ( int i = 0; i < size; i++ )
cout << arr[i] << ' ';
cout << endl;
}
void permute(int v[], int n)
{
if (n == 1) {
printArray(v, SIZE);
} else {
for (int i = 0; i < n; i++) {
permute(v, n-1);
if (n % 2 == 1) {
swap(v[0], v[n-1]);
} else {
swap(v[i], v[n-1]);
}
}
}
}
int main()
{
int ns[] = {1, 2, 3, 4};
permute(ns, SIZE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment