GATE CSE 2017 Session 2 Q53: Output of a bidirectional bubble sort snippet
- Programming and Data Structures
- 2 marks
- NAT
- No negative marking
Syllabus topics: Searching, sorting and hashing; Programming in C
Question
Consider the following snippet of a C program. Assume that swap(&x, &y) exchanges the contents 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 ________.
Try it: numerical answer: type the value
Show answer and explanation
Answer: 3 (official GATE 2017 final answer key)
Concept used: Both passes swap neighbours that are in increasing order, so the loop is a cocktail-shaker sort that stops only when the array is in descending order.
First step: Work out what order the array is in when no swap happens in a full round, then read off the element at index 3.
Full step-by-step solution
Loading…
Answer from the official final answer key. Found a mistake? Use Report issue and we will fix it.
More questions on Searching, sorting and hashing
Every PYQ on this topic →Share this question
Source: official GATE 2017 Session 2 CS question paper and final answer key, organised by IIT Roorkee. Question paper · Answer key
More Programming and Data Structures PYQs
- 2026 Session 1 · Q23Non-leaf indices in a 1-indexed binary heap with n odd
- 2026 Session 1 · Q24Empty slots after linear-probing inserts with h(x) = (x+7) mod 11
- 2026 Session 1 · Q33Maximum height of a full binary tree with 23 nodes
- 2026 Session 1 · Q34Output of a C function with a shadowed block variable
- 2026 Session 1 · Q39Recursive length of a non-empty singly linked list
- 2026 Session 1 · Q40Third insertion that can never yield a complete BST of 1..15