Ely
Ely

Reputation: 15

Sorting function breaks when I try to change it to reverse alphabetical order?

So I have this function which currently sorts through an array struct I plug into it and sorts it alphabetically as shown:

void string_rearrangement(Employee payroll[], int size)
{
    //declaring temporary struct
    Employee temp;
    int i = 0, j = 0;

    for (i = 0; i <= size; i++)
    {
        for (j = i + 1; j <= size; j++)
        {
            if (strcmp(payroll[i].name, payroll[j].name) >0)
            {
                temp = payroll[i];
                payroll[i] = payroll[j];
                payroll[j] = temp;
            }
        }
    }

}

It works. I've tested it. Here's a screenshot of the output i get when I print the names: https://i.sstatic.net/vS7y7.png

But now I wanted to change it so it would give me the reverse alphabetical order. I thought this would just be changing the strcmp condition to <0 as shown:

            if (strcmp(payroll[i].name, payroll[j].name) <0)

But when I do that, I get some crazy output like this: https://i.sstatic.net/gIUHT.png

The only thing I changed between the code was the >0 so I'm not sure why this is happening.

Upvotes: 0

Views: 30

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545608

for (i = 0; i <= size; i++)
{
    for (j = i + 1; j <= size; j++)

You should almost certainly use < instead of <= here. You’re running over the array bounds and into undefined behaviour. You simply got incredibly lucky that your code worked before you changed the sort order.

Upvotes: 2

Related Questions