GATE | GATE-CS-2016 (Set 1) | Question 51

Let Q denote a queue containing sixteen numbers and S be an empty stack. Head(Q) returns the element at the head of the queue Q without removing it from Q. Similarly Top(S) returns the element at the top of S without removing it from S. Consider the algorithm given below.

The maximum possible number of iterations of the while loop in the algorithm is______

[This Question was originally a Fill-in-the-Blanks question] (A) 16
(B) 32
(C) 256
(D) 64

Answer: (C)

Explanation: The worst case happens when the queue is sorted in decreasing order. In worst case, loop runs n*n times.

Queue: 4 3 2 1
Stack: Empty

3 2 1
4

3 2 1 4
Empty

2 1 4
3

2 1 4 3
Empty

1 4 3
2

1 4 3 2
Empty

4 3 2
1

3 2
1 4

3 2 4
1

2 4
1 3

2 4 3
1

4 3
1 2

3 
1 2 4

3 4 
1 2

4
1 2 3

Empty
1 2 3 4

Leave a Reply

Your email address will not be published. Required fields are marked *