Question

Consider the following snippet of a C program. Assume that swap(&x, &y) exchanges the contents of x and y.

int main() {
    int array[] = {3, 5, 1, 4, 6, 2};
    int done = 0;
    int i;

    while (done == 0) {
        done = 1;
        for (i=0; i<=4; i++) {
            if (array[i] < array[i+1]) {
                swap(&array[i], &array[i+1]);
                done = 0;
            }
        }
        for (i=5; i>=1; i--) {
            if (array[i] > array[i-1]) {
                swap(&array[i], &array[i-1]);
                done = 0;
            }
        }
    }
    printf("%d", array[3]);
}

The output of the program is

Official answer and solution
Official answer
3
From
Official GATE 2017 answer key

Solution

Trace the execution of the bidirectional bubble sort (cocktail shaker sort) on the given integer array.

The array initially is array = {3, 5, 1, 4, 6, 2}. Notice the conditions in the two loops:

  • Forward loop: if (array[i] < array[i+1]) swap(...) sorts elements in descending order (largest first).
  • Backward loop: if (array[i] > array[i-1]) swap(...) also bubbles larger elements toward earlier indices.

Trace iteration by iteration:

  1. Pass 1 - Forward (i from 0 to 4):
    • i=0: array[0]=3 < array[1]=5   ⟹  \implies swap →\to {5, 3, 1, 4, 6, 2}
    • i=1: array[1]=3 > array[2]=1 (no swap)
    • i=2: array[2]=1 < array[3]=4   ⟹  \implies swap →\to {5, 3, 4, 1, 6, 2}
    • i=3: array[3]=1 < array[4]=6   ⟹  \implies swap →\to {5, 3, 4, 6, 1, 2}
    • i=4: array[4]=1 < array[5]=2   ⟹  \implies swap →\to {5, 3, 4, 6, 2, 1}
  2. Pass 1 - Backward (i from 5 down to 1):
    • i=5: array[5]=1 < array[4]=2 (no swap)
    • i=4: array[4]=2 < array[3]=6 (no swap)
    • i=3: array[3]=6 > array[2]=4   ⟹  \implies swap →\to {5, 3, 6, 4, 2, 1}
    • i=2: array[2]=6 > array[1]=3   ⟹  \implies swap →\to {5, 6, 3, 4, 2, 1}
    • i=1: array[1]=6 > array[0]=5   ⟹  \implies swap →\to {6, 5, 3, 4, 2, 1}
  3. Pass 2 - Forward (i from 0 to 4):
    • Swaps 3 and 4 →\to {6, 5, 4, 3, 2, 1}
  4. Pass 2 - Backward (i from 5 down to 1):
    • No elements out of order →\to {6, 5, 4, 3, 2, 1}
  5. Pass 3: Neither loop makes a swap, done remains 1, while loop terminates.

The final array sorted in descending order is:
array = {6, 5, 4, 3, 2, 1}
Index 3 contains:
array[3] = 3

Final answer

3

Common trap

Assuming standard ascending sort order; the comparison array[i] < array[i+1] produces descending order.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2017 Computer Science and Information Technology (CS) Session 2
Question
43 of 65, printed as CS Q.43
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.