-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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