Consider a queue of objects each having an identifier (integer) and a color among the three values (blue, white, red). We want to change the queue so that the blue elements are in the beginning of queue, followed by white elements, and finally red ones, without changing the order in which elements of the same color are enqueued.
Write a function that converts such a queue so it can verify the above property.
Use exclusively the operations of the abstract data type queue.
Example :
The following queue :
\(\begin{array}{c}
\hline
\\
\begin{array}{|c|}
\hline
3\\ \hline
red\\
\hline
\end{array}
\begin{array}{|c|}
\hline
5\\ \hline
blue\\
\hline
\end{array}
\begin{array}{|c|}
\hline
2\\ \hline
red\\
\hline
\end{array}
\begin{array}{|c|}
\hline
6\\ \hline
white\\
\hline
\end{array}
\begin{array}{|c|}
\hline
11\\ \hline
white\\
\hline
\end{array}
\begin{array}{|c|}
\hline
9\\ \hline
blue\\
\hline
\end{array}
\begin{array}{|c|}
\hline
1\\ \hline
white\\
\hline
\end{array}
\begin{array}{|c|}
\hline
4\\ \hline
red\\
\hline
\end{array}
\\
\\
\hline
\end{array}
\
\\
\
\\
becomes
\
\\
\begin{array}{c}
\hline
\\
\begin{array}{|c|}
\hline
5\\ \hline
blue\\
\hline
\end{array}
\begin{array}{|c|}
\hline
9\\ \hline
blue\\
\hline
\end{array}
\begin{array}{|c|}
\hline
6\\ \hline
white\\
\hline
\end{array}
\begin{array}{|c|}
\hline
11\\ \hline
white\\
\hline
\end{array}
\begin{array}{|c|}
\hline
1\\ \hline
white\\
\hline
\end{array}
\begin{array}{|c|}
\hline
3\\ \hline
red\\
\hline
\end{array}
\begin{array}{|c|}
\hline
2\\ \hline
red\\
\hline
\end{array}
\begin{array}{|c|}
\hline
4\\ \hline
red\\
\hline
\end{array}
\\
\\
\hline
\end{array}
\)
Difficulty level
Video recording
This exercise is mostly suitable for students
typedef struct
{
int id;
char *color;
} element;
void sort(queue *q)
{
element e;
queue blue, red, white;
blue=red=white=CreateQueue();
while(Front(*q,&e))
{
DeQueue(q);
if (!strcmp(e.color,"blue")) EnQueue(&blue,e);
else if (!strcmp(e.color,"white")) EnQueue(&white,e);
else EnQueue(&red,e);
}
while(Front(blue,&e))
{
DeQueue(&blue);
EnQueue(q,e);
}
while(Front(white,&e))
{
DeQueue(&white);
EnQueue(q,e);
}
while(Front(red,&e))
{
DeQueue(&red);
EnQueue(q,e);
}
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Solution of a system