Today I was looking for the last exam in the local computer science Olympiad, and I found an interesting problem. In short, he asks, if an integer array is given, to calculate how many inversions it has, where the inversion is a pair of indices i , j such that i > j and A[i] < A[j] . Unofficially, the number of inversions is the number of pairs that are out of order. I initially made the O(n²) solution (yes, naive), but, seeing that it would not fit the input size well, I thought about the problem a bit more and then realized that it could be done in O(n log n) time according to the merge sort option, which handles input size perfectly.
But, seeing input restrictions ( n integers between 1 and M and no duplicates), I was wondering if my solution is optimal, or do you know if there is any other solution to this problem that is superior to O(n log n) lead time?
language-agnostic sorting algorithm
Luiz Rodrigo
source share