Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple code to detect the permutation sign

Tags:

algorithm

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.

like image 519
Wirawan Purwanto Avatar asked Apr 22 '26 14:04

Wirawan Purwanto


2 Answers

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.

like image 72
Sayakiss Avatar answered Apr 24 '26 09:04

Sayakiss


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

like image 30
Colonel Panic Avatar answered Apr 24 '26 09:04

Colonel Panic