Created
September 6, 2013 08:30
-
-
Save byelims/6461065 to your computer and use it in GitHub Desktop.
a simple way to generate permutations
This file contains 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 <stdio.h> | |
void print_array(int array[], int n) | |
{ | |
int i; | |
for (i = 0; i < n; i++) { | |
printf("%d%s", array[i], i != n-1 ? " " : "\n"); | |
} | |
} | |
void swap(int *a, int *b) | |
{ | |
int t; | |
t = *a; | |
*a = *b; | |
*b = t; | |
} | |
void permute(int array[], int n, int level) | |
{ | |
int i; | |
if (level == n-1) { | |
print_array(array, n); | |
return; | |
} | |
for (i = level; i < n; i++) { | |
swap(&array[i], &array[level]); | |
permute(array, n, level + 1); | |
swap(&array[i], &array[level]); | |
} | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
int a[] = {1, 2, 3, 4, 5}; | |
permute(a, 5, 0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment