Avoxy λ Avoxy λ - 3 months ago 14
C Question

Sorting a stack in descending order

I'm having trouble sorting a stack in descending order, sorting works with the help of another stack.

here is the sorting code:

void* sort(stack_type* stack, stack_type* auxiliary) {
int* element = NULL;
while(!is_empty(stack)) {
element = pop(stack);
while(!is_empty(auxiliary) && head(auxiliary) > element) {
push(pop(auxiliary), stack);
}
push(element, auxiliary);
}
}


the output is thus:

| -4 |
| -45 |
| 356 |
| 87 |
| 76 |
| 54 |
| 34 |
| 22 |
| 8 |
| 2 |


but i want so:

| 356 |
| 87 |
| 76 |
| 54 |
| 34 |
| 22 |
| 8 |
| 2 |
| -4 |
| -45 |


here is the gist with complete code: https://gist.github.com/avoxy/380e96a87cb3c6cc1f4a62c02fb6428d

thx guys

Answer

You are sorting by the pointers, not by the pointed-to values. In fact, you don't have pointed-to values in this case, which gives rise to the question why to use pointers at all. Anyway, this is the problematic piece of code:

push((int*) -45, stack);

Pointers will mostly be not negative. So, this cast will cause an underflow and, depending on your compiler, will result in a large positive pointer. As such, this pointer will be larger than any of the other pointers you use (except the -4).

Summarizing: Do not sort by pointers (unless you really know what you're doing). Do not use pointers to represent plain integers.