简体   繁体   English

C程序编号没有正确排序数组

[英]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: 关注Lee Daniel Crocker的评论,你应该动态地比较smallPosition而不是i的值,以便它总是指向剩余的最小项:

    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: 您应该在if语句中移动交换代码:

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. 在冒泡排序中,交换当前值的值大于下一个值,如果执行此操作直到到达数组末尾,则数组将被排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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