Number of swaps in Bubble Sort

algorithm, bubble-sort, c++, math

Solution

The best way to get the answer is by running the bubble-sort algorithm itself and including a counter after the swap() call. Your calculation function would (a) need almost as long as the sort itself (depending on the runtime of swap() vs. getprob()) and (b) miss the point that the order of the elements changes while sorting.

Btw, the exact number of swap() calls depends on the data you need to sort - you have n*(n-1)/2 comparisions and any of them could result in a swap (on average, half of the time you need to swap the compared elements).

Problem

I have a version of bubble sort: ``` int i, j; for i from n downto 1 { for j from 1 to i-1 { if (A[j] > A[j+1]) swap(A[j], A[j+1]) } } ``` I want to calculate the expected number of swaps using the above version of bubble sort. The method used by me is shown below : ``` // 0 based index float ans = 0.0; for ( int i = 0; i < n-1; i++ ) { for ( int j = i+1; j < n; j++ ) { ans += getprob( a[i], a[j]); // computes probability that a[i]>a[j]. } } ``` Am i going the correct way or am I missing something?

Original source