algorithm - A simple code to detect the permutation sign -
supposed have array of integers:
1 2 5 3 7 6 what simple enough algorithm determines if or odd permutation of numbers in sorted fashion (i.e. 1 2 3 5 6 7)? performance not terribly important here; i'd rather have simple code.
simple code(assume n numbers stored in array a):
int f() { int cnt=0; for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) if (a[i]>a[j]) cnt++; return cnt%2; } if f() returns 0, permutation , returns 1, odd.
Comments
Post a Comment