Created
December 28, 2014 18:56
-
-
Save andy0130tw/5adb4edbc0bebad77d7f to your computer and use it in GitHub Desktop.
non-recursion n! permutation in C
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> | |
#include<time.h> | |
void roll(int a[],int l,int r){ | |
//roll [l,r) leftward | |
int tmp=a[l],i; | |
for(i=l;i<r-1;i++) | |
a[i]=a[i+1]; | |
a[r-1]=tmp; | |
} | |
void rollR(int a[],int l,int r){ | |
//roll [l,r) rightward | |
int tmp=a[r-1],i; | |
for(i=r-1;i>l;i--) | |
a[i]=a[i-1]; | |
a[l]=tmp; | |
} | |
void print(int a[],int len){ | |
int i; | |
for(i=0;i<len;i++){ | |
printf("%2d ",a[i]); | |
} | |
printf("\n"); | |
} | |
int main(){ | |
int n,i,rb; | |
long long int cnt=0; | |
scanf("%d",&n); | |
int a[n]; | |
//initialize values | |
for(i=0;i<n;i++) | |
a[i]=i+1; | |
printf("Listing %d! permutation\n",n); | |
clock_t start=clock(); | |
while(1){ | |
rb=n; | |
for(i=0;i<n;i++){ | |
cnt++; | |
roll(a,0,n); | |
} | |
while(a[rb-1]==rb&&rb>0){ | |
rb--; | |
roll(a,0,rb); | |
} | |
if(rb==0) | |
break; | |
} | |
printf("---\nDone(%.2lf ms). %d permutations.",(double)(clock()-start)/CLK_TCK*1e3,cnt); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment