Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculating the number of “inversions” in a permutation

Tags:

Let A be an array of size N. we call a couple of indexes (i,j) an "inverse" if i < j and A[i] > A[j]

I need to find an algorithm that receives an array of size N (with unique numbers) and return the number of inverses in time of O(n*log(n)).

like image 484
Shai Balassiano Avatar asked Jun 29 '11 16:06

Shai Balassiano


People also ask

How do you calculate inversions?

For every element, find the count of elements smaller than the current number up to that index using another loop. Sum up the count of inversion for every index. Print the count of inversions.

What is the expected number of inversions in any permutation on n elements?

What is the expected number of inversions in any permutation on n elements ? Explanation: There are n(n-1)/2 pairs such that i < j. For a pair (ai, aj), probability of being inversion is 1/2.

How do you find the inverse of a permutation matrix?

Since interchanging two rows is a self-reverse operation, every elementary permutation matrix is invertible and agrees with its inverse, P = P−1 or P2 = I.

Which determine the number of inversions within a given array?

If we are given an array sorted in reverse order, the inversion count will be the maximum number in that array. The inversion count for an array sorted in increasing order will be zero. Inversion will be counted if arr[i] is greater than arr[j] where i is lesser than j.


1 Answers

You can use the merge sort algorithm.

In the merge algorithm's loop, the left and right halves are both sorted ascendingly, and we want to merge them into a single sorted array. Note that all the elements in the right side have higher indexes than those in the left side.

Assume array[leftIndex] > array[rightIndex]. This means that all elements in the left part following the element with index leftIndex are also larger than the current one in the right side (because the left side is sorted ascendingly). So the current element in the right side generates numberOfElementsInTheLeftSide - leftIndex + 1 inversions, so add this to your global inversion count.

Once the algorithm finishes executing you have your answer, and merge sort is O(n log n) in the worst case.

like image 168
IVlad Avatar answered Sep 22 '22 03:09

IVlad