Counting inversions in an array

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

    I had a question similar to this for homework actually. I was restricted that it must have O(nlogn) efficiency.

    I used the idea you proposed of using Mergesort, since it is already of the correct efficiency. I just inserted some code into the merging function that was basically: Whenever a number from the array on the right is being added to the output array, I add to the total number of inversions, the amount of numbers remaining in the left array.

    This makes a lot of sense to me now that I've thought about it enough. Your counting how many times there is a greater number coming before any numbers.

    hth.

提交回复
热议问题