Consider the following snippet of a C program. Assume that swap exchanges the content of and :
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 .
After this pass, the array becomes:{5, 3, 4, 6, 2, 1} - Backward pass (i = 5 down to 1): Swaps elements if .
After this pass, the array becomes:{6, 5, 3, 4, 2, 1}
- Forward pass (i = 0 to 4): Swaps elements if .
- Iteration 2:
- Forward pass (i = 0 to 4): Swaps and 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.
- Forward pass (i = 0 to 4): Swaps and at index 2.
- Iteration 3: No swaps occur in either pass, so
doneremains1and 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.
