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))
.
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 ? Explanation: There are n(n-1)/2 pairs such that i < j. For a pair (ai, aj), probability of being inversion is 1/2.
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.
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.
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.
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