GATE / CS ARCHIVE

GATE CSE 1993 / QUESTION 15

Comparison recurrence for recursive bubble sort

Algorithms · Searching, Sorting & Selection · Full GATE CSE 1993 paper

GATE 1993, Q15 5 marks · Descriptive
Report issue

Searching, Sorting & Selection

Question 15, GATE 1993: The printed procedure loops i=1 to n−1, tests A[i]>A[i+1], swaps adjacent entries if true, and then unconditionally calls bubblesort(n−1). It has no base-case guard and prints temp : A[i] instead of a valid assignment. Let an count executions of the if test. Give a recurrence and solve it.
Question 15, GATE 1993: The printed procedure loops i=1 to n−1, tests A[i]>A[i+1], swaps adjacent entries if true, and then unconditionally calls bubblesort(n−1). It has no base-case guard and prints temp : A[i] instead of a valid assignment. Let an count executions of the if test. Give a recurrence and solve it.
Tap to enlarge
Answer & solution

Answer: With base case a1=0, an=a(n−1)+n−1, giving n(n−1)/2 comparisons (the printed recurrence has no base case) (no official key was published)

First distinguish the literal source from its conventional intended algorithm. As printed, the procedure has no terminating case and contains a malformed temp assignment. It is not a valid terminating Pascal sort. After correcting assignment punctuation and adding a guard such as "if n<=1 then return", the standard comparison-count question is well-defined.

For the repaired algorithm, one call on n>=2 performs exactly n−1 tests A[i]>A[i+1], irrespective of the data or whether the consequent swap executes. It then calls the procedure once on n−1. Therefore a1=0 and an=a(n−1)+(n−1), n>=2. Equivalently a0=0 may be used with the guard. Repeated substitution gives
an=(n−1)+(n−2)+...+1+a1=n(n−1)/2.
An induction verifies the closed form: it is 0 at n=1; if a(n−1)=(n−1)(n−2)/2, adding n−1 yields n(n−1)/2. Thus the comparison count and running time are Theta(n2), even for sorted input, because there is no early-exit flag. The swaps, unlike tests, depend on data: zero for sorted input, up to n(n−1)/2 for reverse order with distinct entries.

A complete repaired algorithm is:
procedure bubblesort(A,n):
    if n<=1: return
    for i=1,...,n-1:
        if A[i]>A[i+1]:
            temp:=A[i]
            A[i]:=A[i+1]
            A[i+1]:=temp
    bubblesort(A,n-1)

Each pass moves the largest of the first n entries to position n; recursion sorts the preceding prefix. Without the added guard the recursive calls proceed through n=1,0,−1,... (or fail because of the index type/stack), so the printed code does not successfully finish. The finite formula is explicitly for the repaired intended algorithm, not a claim that the literal program terminates.

Original paper, page 11