GATE / CS ARCHIVE

GATE CSE 1995 / QUESTION 12

Trace five bubble-sort passes

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

GATE 1995, Q12 5 marks · Descriptive
Report issue

Searching, Sorting & Selection

Question 12, GATE 1995: Sort 92,37,52,12,11,25 in ascending order by bubble sort, giving the sequence after each of the first five passes. State traversal direction.
Tap to enlarge
Answer & solution

Answer: Left-to-right passes: 37 52 12 11 25 92; 37 12 11 25 52 92; 12 11 25 37 52 92; 11 12 25 37 52 92; 11 12 25 37 52 92. (no official key was published)

Use the usual left-to-right version: compare adjacent entries and swap whenever the left entry exceeds the right. After one full pass, the largest element of the active prefix has bubbled to its final rightmost position. Shorten the active prefix by one for the next pass.

Pass 1: 37,52,12,11,25,92.
Pass 2: 37,12,11,25,52,92.
Pass 3: 12,11,25,37,52,92.
Pass 4: 11,12,25,37,52,92.
Pass 5: 11,12,25,37,52,92.
For example, in pass 1, 92 is successively swapped with 37,52,12,11,25. In pass 2, 52 moves to the penultimate position. A no-swap early-exit implementation would detect completion on pass 5 in this trace.

The source does not specify pass direction. The equally valid right-to-left version bubbles minima left and gives: [11,92,37,52,12,25], [11,12,92,37,52,25], [11,12,25,92,37,52], [11,12,25,37,92,52], [11,12,25,37,52,92]. Both reach the same sorted list; intermediate pass answers depend on the convention.

Original paper, page 7