supposed I have an array of integers:
1 2 5 3 7 6
What is a simple enough algorithm that determines if this is an even or odd permutation of the numbers in sorted fashion (i.e. 1 2 3 5 6 7)? Performance is not terribly important here; I'd rather have a simple code.
Simple Code(Assume n numbers are 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, then it is even permutation and returns 1, then it is odd.
According to Wikipedia, the sign is determined by the number of inversions (pairs of elements out of order). That gives an O(n**2) algorithm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With