The GATE Grind

GATE 2017 CS (CS2) – Question 53

Programming and Data Structures · Programming in C · 2 marks · Numerical answer

swap exchanges its two arguments. Find the output.

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]);
}

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 3.0 to 3.0

Explanation

The forward and backward passes swap adjacent out-of-order pairs for descending order. If any swap occurs, another full iteration runs. On exit the array is 6,5,4,3,2,1. Index three is the fourth element, 3, which is printed.

More Programming in C questions

All Programming in C questions →