Counting inversions in an array

前端 未结 30 1990
死守一世寂寞
死守一世寂寞 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:49

    C++ Θ(n lg n) Solution with the printing of pair which constitute in inversion count.

    int merge(vector&nums , int low , int mid , int high){
        int size1 = mid - low +1;
        int size2= high - mid;
        vectorleft;
        vectorright;
        for(int i = 0  ; i < size1 ; ++i){
            left.push_back(nums[low+i]);
        }
        for(int i = 0 ; i & nums , int low , int high){
        if(high>low){
            int mid = low + (high-low)/2;
            int left = inversion_count(nums,low,mid);
            int right = inversion_count(nums,mid+1,high);
            int inversion = merge(nums,low,mid,high) + left + right;
            return inversion;
        }
        return 0 ;
    }
    

提交回复
热议问题