Consider the following snippet of a C program. Assume that swap \((\&x, \&y)\)…
2017
Consider the following snippet of a C program. Assume that swap \((\&x, \&y)\) exchanges the content 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 _______
Attempted by 31 students.
Show answer & explanation
Correct answer: 3
Key idea: the loops implement a bidirectional bubble (cocktail shaker) process but with comparisons arranged to move larger elements toward the start, so the array ends up sorted in descending order.
Start: [3, 5, 1, 4, 6, 2]
After the forward pass (swap when left < right): [5, 3, 4, 6, 2, 1]
After the backward pass (swap when right > left): [6, 5, 3, 4, 2, 1]
Next forward pass completes the descending order: [6, 5, 4, 3, 2, 1]
No further swaps occur, so the loop ends with the array in descending order.
Conclusion: the element at index 3 is 3, so the program prints 3.
A video solution is available for this question — log in and enroll to watch it.