Skip to content
Official PYQ · 2017

GATE CS 2017 Set 2 Q43 — Programming in C

Explain with AI

Consider the following snippet of a C program. Assume that swap (&x,&y)(\&x, \&y) exchanges the content of xx and yy:

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 _______

View worked solution

Answer: 3

The given program implements the Cocktail Shaker Sort (a bidirectional variation of Bubble Sort) to sort the array in descending order.

Let's trace the array elements step-by-step:

  • Initial Array: {3, 5, 1, 4, 6, 2}
  • Iteration 1:
    • Forward pass (i = 0 to 4): Swaps elements if array[i]<array[i+1]array[i] < array[i+1].
      After this pass, the array becomes: {5, 3, 4, 6, 2, 1}
    • Backward pass (i = 5 down to 1): Swaps elements if array[i]>array[i−1]array[i] > array[i-1].
      After this pass, the array becomes: {6, 5, 3, 4, 2, 1}
  • Iteration 2:
    • Forward pass (i = 0 to 4): Swaps 33 and 44 at index 2.
      After this pass, the array becomes: {6, 5, 4, 3, 2, 1}
    • Backward pass (i = 5 down to 1): No swaps occur because the array is already sorted in descending order.
  • Iteration 3: No swaps occur in either pass, so done remains 1 and the loop terminates.

At the end of the program, the array is {6, 5, 4, 3, 2, 1}. The value at array[3] is 3.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions