简体   繁体   中英

C Program numbers not sorting array correctly

I have an array of structs for products that I am trying to sort by name, type, price, and quantity. Name and type work, but price and quantity aren't working. My code is:

else if (sort == sortByPrice)
{
    for (int i = 0; i < numProducts; i++)
    {
        int smallPosition = i;
        for (int x = i + 1; x < numProducts; x++)
        {
            if (list[i].price > list[x].price)
            {
                smallPosition = x;
            }
        }

        temp = list[i];
        list[i] = list[smallPosition];
        list[smallPosition] = temp;
    }

}
else if (sort == sortByQty)
{
    for (int i = 0; i < numProducts; i++)
    {
        int smallPosition = i;
        for (int x = i + 1; x < numProducts; x++)
        {
            if (list[i].qty > list[x].qty)
            {
                smallPosition = x;
            }
        }

        temp = list[i];
        list[i] = list[smallPosition];
        list[smallPosition] = temp;
    }
}

Can anyone tell me why it doesn't work/how to fix it?

Following up on Lee Daniel Crocker 's comment, you should dynamically compare with the value at smallPosition instead of i so that it will always point to the smallest remaining item:

    int smallPosition = i;
    for (int x = i + 1; x < numProducts; x++)
    {
        if (list[smallPosition].price > list[x].price)
        {
            smallPosition = x;
        }
    }

You should move the swap code inside the if statement:

for (int i = 0; i < numProducts; i++)
{
    for (int x = i + 1; x < numProducts; x++)
    {
        if (list[i].price > list[x].price)
        {
            temp = list[i];
            list[i] = list[X];
            list[X] = temp;
        }
    }

}

Just use bubble sort.

In the bubble sort you swap the values of the current value is bigger than the next one, if you do this action until you get to the end of the array then the array will be sorted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM