Morty has an array of length n filled with distinct numbers in any random order. He gives the array to Rick who sorts it using bubblesort algorithm. Bubblesort takes an array {a1, a2, a3 .. an} of numbers and repeatedly swaps adjacent numbers that are inverted (i.e., in the wrong relative order) until there are no remaining inversions.
What is the expected number of swaps performed by Rick?
Try to solve this problem yourself before moving on to the solution below
.
.
.
.
.
Solution
A pair (i,j) is an inversion in array D if D[i] > D[j] and i < j
For a permutation of length n, let I_ij if (𝑖,𝑗) is an inversion. Then
E[I_ij ] = 𝑃((𝑖,𝑗) is an inversion) = 1/2
This is easy to see by symmetry: for any pair (𝑖,𝑗) that's an inversion, (𝑗,𝑖) is not an inversion.
Now use the linearity of expectation to solve for all the pairs
Simple calculations give the result
Another solution
Every permutation 𝜋 with 𝑁 inversions can be read backwards to give a permutation with 𝑛C2−𝑁 inversions. This gives a 1-1 map between permutations with 𝑁 inversions and 𝑛C2−𝑁 inversions. Then by symmetry it's clear that the expected value is nC2 / 2.
.
.
😃 Over to you: Were you able to solve this?
👉 If you liked this post, don’t forget to leave a like ❤️. It helps more people discover this newsletter on Substack and tells us that you appreciate solving these weekly questions. The button is located towards the bottom of this email.
👉 If you love reading this newsletter, feel free to share it with friends!
Another approach:
As the chances of each swap is independent (and =1/2).
Lets see for the first loop of comparisions, how many swaps are possible:
As there are n numbers, there will be n-1 comparisons, thus average number of swaps coming to be as (n-1)/2.
Similarly in the next loop, we have n-2 comparisons, then n-3, n-4,.. up till 1.
Thus, the total number of comparisons turning out to be sum of first n-1 numbers, i.e. n*(n-1)/2.
And the average number of swaps being the half of it, we get our answer to be n(n-1)/4.
Good one