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?](../../assets/questions/CS-2017-S2-Q53-1.webp)
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.