Consider an array a of integers. A pair (i,j) is called an inversion in A if i < j and A[i] > A[j].
For every position ‘i’ in the array there are two possible candidates: a[i] with probability p[i] and a[i]+x with probability 1-p[i].
Now I have to calculate expected number of inversions.
Given a[i] and p[i] for every index i and an integer x.
I know the O(n^2) approach (check every legal possible pair).
Also, I know the O(nlogn) approach to calculate the number of inversions in an array in which all the elements are predetermined with 100% probability. It is done by modifying merge sort.
I want to know an approach better than n squared. Please let me know.
This can be done with a simple modification to the standard merge-sort based algorithm for counting inversions, where we assign a weight to each value and compute the sum of
W[i]*W[j]fori<j,A[i]>A[j](when each weight is 1, we get the normal count). Instead of adding to the count the number of elements remaining in the left array, we add the sum of the weights for these elements multiplied by the weight of the element in the right array we are processing.To use this algorithm to solve the posed problem, simply create an array of twice the size, where each element in the original array is replaced by two elements (in sorted order), with weights given by the probabilities.