Counting inversions in an array

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

    The easy O(n^2) answer is to use nested for-loops and increment a counter for every inversion

    int counter = 0;
    
    for(int i = 0; i < n - 1; i++)
    {
        for(int j = i+1; j < n; j++)
        {
            if( A[i] > A[j] )
            {
                counter++;
            }
        }
    }
    
    return counter;
    

    Now I suppose you want a more efficient solution, I'll think about it.

提交回复
热议问题