GATE / CS ARCHIVE

GATE CSE 2017 SET 2 / QUESTION 43

GATE CSE 2017 Set 2 Q43

Programming in C · Arrays & Strings · Full GATE CSE 2017 Set 2 paper

GATE 2017 Set 2, Q43 2 marks · NAT
Report issue

Arrays & Strings

Question 43, GATE 2017: C code initializes array[]={3,5,1,4,6,2}, done=0. While done==0, set done=1; for i=0..4, if array[i]<array[i+1], swap them and set done=0; then for i=5..1 descending, if array[i]>array[i-1], swap them and set done=0. After the loop printf("%d",array[3]). swap exchanges the two addressed values. What is printed?
Tap to enlarge
Answer & solution

Official answer: 3.0

Our answer: 3

Step through it (32 steps)

1. Both passes correct adjacent pairs toward descending order. In the forward pass a smaller value on the left is swapped right; in the backward pass a larger value on the right is swapped left. The initial forward pass changes [3,5,1,4,6,2] into [5,3,4,6,2,1].

2. Its backward pass produces [6,5,3,4,2,1]. In the next forward pass the remaining out-of-order pair 3,4 swaps, producing [6,5,4,3,2,1]; the backward pass then makes no changes.

3. Because a swap occurred, done remains 0 and one more full iteration verifies that no swaps are needed. Every strict adjacent inversion swap decreases a finite inversion count, so termination is justified. The final zero-based index 3 contains 3, which is printed. Index 3 means the fourth element, not the third.

Original paper, page 17 · Answer key