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?
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).
Maybe this helps. Basically this provides a framework to run bubble sorts on a set of simulation datasets and to calculate the swap probability.
Let this probability = p
Then to find the expected number of swap operations, you need to apply this on a real dataset. Let n be the size of this dataset.
Then expected number = swapProbability * n * n
n*n comes because the bubble sort has n * n number of expected operations.
float computeSwapProbability()
{
int aNumSwaps = 0
int aTotalNumberOfOperations = 0
For all simulation datasets
{
int i, j;
for i from n downto 1
{
for j from 1 to i-1
{
aTotalNumberOfOperations++
if (A[j] > A[j+1])
{
swap(A[j], A[j+1])
aNumSwaps++
}
}
}
}
return (float)aNumSwaps/aTotalNumberOfOperations;
}
The best way to count swap is to include counter variable inside the if condition for swap.
int swapCount=0;
for (i = 0; i < (length-1); ++i) {
for (j = 0; j < (length-i-1); ++j) {
if(array[j] > array[j+1]) {
temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
swapCount++;
}
}
}
printf("Swap count : %d" ,swapCount);