Counting inversions in an array

前端 未结 30 2413
死守一世寂寞
死守一世寂寞 2020-11-22 04:14

I\'m designing an algorithm to do the following: Given array A[1... n], for every i < j, find all inversion pairs such that A[i] > A[j]

30条回答
  •  时光取名叫无心
    2020-11-22 04:39

    Here is one possible solution with variation of binary tree. It adds a field called rightSubTreeSize to each tree node. Keep on inserting number into binary tree in the order they appear in the array. If number goes lhs of node the inversion count for that element would be (1 + rightSubTreeSize). Since all those elements are greater than current element and they would have appeared earlier in the array. If element goes to rhs of a node, just increase its rightSubTreeSize. Following is the code.

    Node { 
        int data;
        Node* left, *right;
        int rightSubTreeSize;
    
        Node(int data) { 
            rightSubTreeSize = 0;
        }   
    };
    
    Node* root = null;
    int totCnt = 0;
    for(i = 0; i < n; ++i) { 
        Node* p = new Node(a[i]);
        if(root == null) { 
            root = p;
            continue;
        } 
    
        Node* q = root;
        int curCnt = 0;
        while(q) { 
            if(p->data <= q->data) { 
                curCnt += 1 + q->rightSubTreeSize;
                if(q->left) { 
                    q = q->left;
                } else { 
                    q->left = p;
                    break;
                }
            } else { 
                q->rightSubTreeSize++;
                if(q->right) { 
                    q = q->right;
                } else { 
                    q->right = p;
                    break;
                }
            }
        }
    
        totCnt += curCnt;
      }
      return totCnt;
    

提交回复
热议问题