Okay, I was right, and wrong. It does "unnecessarily" push the numbers down, eg, even when you insert the highest number, it bumps the zeros down.
But this does not lead to the complications I hypothesized, so it is not really a bug.
You could eliminate it anyway by enclosing in a condition:
Code:
if (pos != rear) {
[the for loop]
}
Also -- I presume you are aware of this -- if one of the numbers added to the queue is zero, the algorithm falls apart (try it). That doesn't matter if it is intended for time stamps or values guaranteed to be greater than zero.
If you are curious, here's the code I used to test. Notice a "!" is printed inside the for loop, indicating when it occurs. It occurs the first time, even though there are no numbers to push down (etc).
Code:
#include <stdio.h>
#define MAX 10
unsigned int msgArray[10] = {0};
int rear = 0;
void addToQueue( unsigned int num )
{
int pos = 0;
int move = 0;
printf("add: %d\n",num);
if(rear<MAX)
{
/*find position to insert*/
for (pos=0; num>=msgArray[pos]&& pos<=rear && msgArray[pos]!=0 ; pos++)
{
}
/*shift cells*/
for (move=rear; move>=pos; move--)
{
printf("!"); fflush(stdout);
msgArray[move+1]=msgArray[move];
}
/*copy new int*/
msgArray[pos]=num;
rear++;
}
else
{
printf("\nNo more room to add data", "");
}
}
int main(int argc, char *argv[]) {
unsigned int testdata[10] = { 1234, 3, 345, 999999, 89231, 890, 666, 1, 8765, 10 };
int i,j;
for (j=0; j<10; j++) {
addToQueue(testdata[j]);
for (i=0; i<10; i++) printf("%d\n", msgArray[i]);
getchar();
}
return 0;
}
ps. you don't have to use empty brackets with the insertion loop, you can just write:
Code:
for (pos=0; num>=msgArray[pos]&& pos<=rear && msgArray[pos]!=0 ; pos++);