Regard the applied swap()
to a[i]
and a[i+1]
as a bubble-up of a[i]
.
Now, asking how many swaps are going to happen is the same as asking how many bubble-up operations are going to happen. Well, and how many do we have of those?
Each a[i]
will bubble-up for each position j > i
, where a[j]<a[i]
. In words a[i]
will bubble-up for each position to the right, where the elements value at that position is smaller than a[i]
itself. A pair of elements satisfying this condition is what is known as an inversion of a[]
.
So reformulating your question we could ask: What is the total number of inversions in a[]
? (a.k.a. What is the inversion number of a[]
?)
This is a well known problem and besides some obvious approaches running in O(n^2) a typical approach to this problem is to tweak merge-sort a bit in order to find this number. And since merge-sort runs in O(n*log(n)) you get the same running time to find the inversion number of a[]
.
Now that you know that you can tweak merge-sort, I suggest you give it a try on your own on how to do it exactly.
Hint: The main question you have to answer is: When positioning a single element during a merge-step of two arrays, how many inversion did I fix? Then simply add up all of those.
In case you still are stuck after giving it some thought, you can have a look at some full blown solutions here: