Search code examples
algorithmanalysisbubble-sort

Running Time Analysis of Modified Bubble Sort


I am working on a homework assignment in which I am required to find the number of comparisons made by a modified bubble sort on a data set of size n. The data set to be considered is a sorted list where the first and last elements are swapped for example: 52341. Below is the pseudocode for the algorithm:

i <- n-1; new_i <- i
while i > 0 do 
    for j=1 to i do
        if A[j] > A[j+1] do
            A[j] <=> A[j+1]
            new_i <- j
        endif
    endfor
    i <- new_i - 1; new_i <- i
endwhile

A is the data set and <=> is a swap.

I am trying to find a way to represent this algorithm with summations to be simplified into an expression of the amount of comparisons on the given type of data set.

Without giving the answer, can anybody push me in the right direction?


Solution

  • In your Bubblesort implementation, the number of comparisons is completely determined alone by the size of the input, i.e. the order of the elements in the input list doesn't matter.

    If you can prove this point (which is not very hard), it suffices to count the number of comparisons for an input list of size N. Since we have already shown that order doesn't matter, this is again fairly easy:

    We have two loops, the outer while loop and the inner for loop. The outer loop goes from n to 1 (or n-1 to 0, but certainly not from n-1 to 1, as suggested by your code), i.e. we have N iterations. The inner loop goes from 1 to i.

    Hence we have N comparisons in the first iteration of the outer loop, N-1 in the second, N-2 in the third, ..., 0 in the N-N'th.

    I presume that you came this far by yourself. Otherwise, you're screwed anyway.

    What your teacher now wants to see is that you know the following formula, the so called "Gaußsche Summenformel," also known as "Gauss Sum":

    N + (N-1) + (N-2) + ... + (N-N+1) + (N-N) = N^2/2 + N/2

    So what you're supposed to do here is:

    • show that the number of comparisons only depends on the size of the input
    • show that the number of comparisons equals N + (N-1) + (N-2) + ... + (N-N+1) + (N-N)
    • mention that this is the same as N^2/2 + N/2, referring to Mr. Gauß.

    ;-)