Possible Duplicate:
Counting inversions in an array
This is a programming question that I had when I was interviewed by a company for a developer job few months ago.
Given an array A of N integers, an inversion of the array is defined as any pair of indexes (a,b) such that a<b and A[b]<A[a].
Write a function:
int inversion_count(int A[], int n);
which computes the number of inversions in A, or returns -1 if such number exceeds 1,000,000,000. For example, in the following array
A[0]=-1 A[1]=6 A[2]=3 A[3]=4 A[4]=7 A[5]=4
there are four inversions:
(1,2) (1,3) (1,5) (4,5)
so the function should return 4.
I solved this question in a very common way: using double loop.
int i, j;
long count;
for (i = 0; i < n; i++) {
for (j = i+1; j < n; j++) {
if (A[i] > A [j]) count++;
if (count > 1000000000) break; // exit loop
}
if (count > 1000000000) break; // exit loop
}
if (count > 1000000000) return -1;
else return count;
So the running time of it is : O (nsquare), and I was told that it was not efficient. I am now thinking of a different way to solve this problem, maybe using an n log n algorithm, but I haven't figured it out yet. Any ideas?
This answer explains a O(n log n) algorithm: Counting inversions in an array.
The trick is to first sort (O(n log n)), and then use binary search to find elements (also O(n log n)) resulting in O(n log n).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With