I want to sort list items by their priority, which the user types in, and it does that well. However, when there is more than one item with the same priority, it doesn’t sort them by order of arrival like it’s supposed to.
I’m sorry if I’m not making this clear enough so you can understand. The names of the variables are in portuguese, so if you don’t understand someting, please ask.
Here is the code:
typedef struct pedido pedido, *ppedido;
struct pedido{
char id[5];
int prioridade;
int mesa, n_pratos;
struct prato *prato[TAM];
ppedido prox;
};
struct prato{
char id[5];
};
ppedido novo_pedido(ppedido lista)
{
ppedido novo, aux, anterior = NULL;
int i;
novo = (struct pedido*)malloc(sizeof(pedido));
if(novo == NULL){
printf("Erro na alocacao de memoria...\n");
return;
}
printf("Number of menus: ");
scanf("%d", &novo->n_pratos);
printf("Table number: ");
scanf("%d", &novo->mesa);
printf("Priority of request? ");
scanf("%d", &novo->prioridade);
printf("Introduza o ID do pedido: ");
scanf("%s", &novo->id);
for(i=0;i<novo->n_pratos;i++){
printf("ID of menu %d: ", i+1); //something like "M1, M4..." doesn't matter
scanf("%s", &novo->prato[i]);
fflush(stdin);
}
novo->prox=NULL;
if(lista == NULL || novo->prioridade > lista->prioridade) {
novo->prox = lista;
lista = novo;
}
else
{
aux = lista;
while(aux != NULL && novo->prioridade < aux->prioridade) //this is where it should be sort requests by their priority and order of arrival
aux = aux->prox;
novo->prox = aux->prox;
aux->prox = novo;
}
return lista;
}
I think you want to change this:
To:
This way it will go past all of the the ones of the same priority and be put closer to the end of the list. This will keep a reference to aux when you traverse to the end of the list.
I assume in your search you stop as soon as you find the highest priority.
This assumes the order of entry into the list is the same as the order of arrival.