IAE Academy

GATE 2024 DA Q.45: solution and answer

GATE 2024 · DAQ.45 · 2 marks · MCQ

Consider the following sorting algorithms:

(i) Bubble sort
(ii) Insertion sort
(iii) Selection sort

Which ONE among the following choices of sorting algorithms sorts the numbers in the array [4, 3, 2, 1, 5] in increasing order after exactly two passes over the array?

  1. (A)

    (i) only

  2. (B)

    (iii) only

  3. (C)

    (i) and (iii) only

  4. (D)

    (ii) and (iii) only

See the question in the paper

Answer and solution

ANSWER

Only selection sort sorts after exactly two passes, so the answer is (B), (iii) only.

Official answer: BSource: Official answer key, GATE 2024 DA (IISc Bengaluru)

  1. Trace each algorithm on and look at the array after exactly two passes. A pass of bubble sort is one left-to-right sweep of adjacent compares. A pass of insertion sort inserts the next element into the sorted prefix. A pass of selection sort puts the minimum of the unsorted part into its final place.

  2. Bubble sort, pass 1: compare and swap, giving . Compare and swap, giving . Compare and swap, giving . Compare and leave it. The array is .

  3. Bubble sort, pass 2: compare and swap, giving . Compare and swap, giving . Compare and and leave both. The array is . The first two entries are still out of order, so bubble sort is not finished.

  4. Insertion sort, pass 1: insert into the sorted prefix , giving .

  5. Insertion sort, pass 2: insert into , giving . The element has not yet been inserted, so the array is not sorted.

  6. Selection sort, pass 1: the minimum of the whole array is . Swap it with the first position, giving .

  7. Selection sort, pass 2: the minimum of the remaining part is . Swap it with the second position, giving . The array is sorted.

  8. Only selection sort has the array fully sorted after exactly two passes, so the answer is (iii) only, which is option (B).

KEY IDEA

Simulate each algorithm for exactly two passes and compare with the sorted array. Selection sort fixes one element per pass in its final place. Here the two smallest elements, and , are fixed in two passes, and the rest, , already happens to be in order.

WATCH OUT FOR

Assuming that bubble sort or insertion sort also finishes in two passes. Bubble sort carries only the largest element to the end each pass, so the small elements and near the right move left by just one place per pass. Insertion sort after two passes has only sorted the first three elements and has not yet looked at .

From the GATE 2024 DA paper. Every question of this paper · Download the full paper · All 18 Sorting & hashing questions, with notes

More Sorting & hashing questions