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?
Explanation : None. 2. What is not true about insertion sort?
So we can generalize that for a cycle of size n, we need at most n – 1 swaps to sort it.
Total 18 swapping required to get the bubble sort.
For example bubble sort algorithm has a complexity of O(n^2). As you see above, two loops are used to sort the array. Let ARRAY_SIZE be n. Then the number of operations is n*(n-1).
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).
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