# How to calculate "expected" number of inversions in a semi-random array of integers?

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.

## Answers

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] for i<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.

I left a comment explaining this, but you can have an O(1) calculation of this if you just use a little bit of math. I'll spare you the work, but, by my calculations, the expected number of inversions in an array of n integers is ((n^2) - (n)) / 4. Sorry for the abundance of parentheses, I just wanted to make sure that was totally clear. I can post the work if you want it, but I figured I'd leave it out if you just need the answer.

So, despite what my comment says, I remembered incorrectly. It's not lg(n).