I'm working on an improved version of merge sort
so that it counts the number of inversions
.
Note: I don't want you to get my homework done, but I have some ideas about this and would love to know whether they make sense at all.
As merge-sort is O(nlogn
I need to adjust it without worsing its overall performance. I think to this I have to insert a test that takes constant time (1)
(1) I test for inversion (upper) with A[i] > A[j] given that i<j
To find the appropriate spot to insert the test I am asking myself: when during the execution of merge sort is guaranteed that the test runs unrelated to n?
I think the only spot where this is true is when the list is split into one-element lists
Hence, I would propose the following algorithm adjustment
use divide-and-conquer and split the list to one elements lists
test A[i] > A[j] as i<j is true for two adjacent lists
Does this make sense at all?
Eventually, I have to carry with the count of inversions until the algorithm terminates. Could someone give me a hint with regard to this problem?
(Intuitively I would give the count to the merge part as the algorithm terminates when merging is complete.)
Cheers, Andrew