Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of swaps in Bubble Sort

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?

like image 248
TheRock Avatar asked Jul 04 '12 14:07

TheRock


People also ask

How many swap are required to sort the given array using bubble sort?

Explanation : None. 2. What is not true about insertion sort?

What is the number of swaps required to sort?

So we can generalize that for a cycle of size n, we need at most n – 1 swaps to sort it.

What are the number of swapping needed to sort the numbers 4 9 8 2 1 in ascending order using bubble sort?

Total 18 swapping required to get the bubble sort.

How do you calculate the number of operations in 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).


1 Answers

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).

like image 145
C. Stoll Avatar answered Sep 25 '22 19:09

C. Stoll