+ 1

Can anyone explain output of the algorithm When input in the queue is contain these numbers as written 100,153,127,143,162 ?

When input is 100,153,127,143,162 Algorithm CHANGE (Queue) { queue size = queue count (queue) count = 0 loop (count< queue size) { dequeue (queue, queue data) if (queue data NOT less than 145) { enqueue (queue, queue data) dequeue (queue, queue data) } else enqueue (queue, queue data) count=count + 1 } return } Answer is 153 can anyone explain how?

5th Sep 2019, 8:22 AM
Preity
Preity - avatar
2 Antworten
+ 1
Well, let's handtrace what happens. Since there are five elements inside the queue, there will be five iterations of the loop. At the beginning of each iteration, the first element at the front is removed. Queue: 162 143 127 153 100 Iteration 1: 162 is at the front -> 162 > 145 -> if-case: 162 is added to the back, 143 (current front element, since 162 was removed) is removed Queue: 127 153 100 162 Iteration 2: 127 is at the front -> 127 < 145 -> else-case: 127 is added to the back Queue: 153 100 162 127 Iteration 3: 153 is at the front -> 153 > 145 -> if-case: 153 is added to the back, and 100 is removed Queue: 162 127 153 Iteration 4: 162 is at the front -> 162 > 145 -> if-case: 162 is added to the back, and 127 is removed Queue: 153 162 Iteration 5: 153 is at the front -> 153 > 145 -> if-case: 153 is added to the back, 162 is removed Queue: 153 Now the loop terminates, and the queue results in only containing 153. Here is a sample program in C++: https://code.sololearn.com/c435C0Uc13In/?ref=app
5th Sep 2019, 8:58 PM
Shadow
Shadow - avatar
+ 1
Shadow thanks for the help it's pretty much clearer and good explanation it help me to understand thanks an heaps 👍
6th Sep 2019, 4:52 AM
Preity
Preity - avatar