The expected number of inversions--From Introduction to Algorithms by Cormen

后端 未结 5 580
北恋
北恋 2020-12-30 03:38

Let A[1 .. n] be an array of n distinct numbers. If i < j and A[i] > A[j], then the pair (i, j) is called an inversion of A. (See Problem 2-4 for more on inv

5条回答
  •  渐次进展
    2020-12-30 04:14

    Even simpler (similar to Aman's answer above, but perhaps clearer) ...

    Let Xij be a random variable with Xij=1 if A[i] > A[j] and Xij=0 otherwise.
    Let X=sum(Xij) over i, j where i < j
    
    Number of pairs (ij)*:               n(n-1)/2
    Probability that Xij=1 (Pr(Xij=1))): 1/2
    By linearity of expectation**:       E(X) = E(sum(Xij))
                                              = sum(E(Xij))
                                              = sum(Pr(Xij=1))
                                              = n(n-1)/2 * 1/2
                                              = n(n-1)/4
    
    *  I think of this as the size of the upper triangle of a square matrix.
    ** All sums here are over i, j, where i < j.
    

提交回复
热议问题