首页 > 解决方案 > 如何对数组中的对象进行冒泡排序?

问题描述

我有点问题。我正在尝试对包含对象的数组进行排序。对象是带有名称、价格和类型的瓶子。用户做出选择,他/她想要将哪个瓶子添加到阵列中。

对于作业,我们必须使用冒泡排序。我已经成功了,只是它只对价格进行排序。整个对象不只是价格本身交换位置。因此,如果 Coca-Cola 的原始价格在列表中是 13,那么在冒泡排序之后它是 10。所以唯一改变或排序的是价格,而不是整个对象,如果这有意义的话。

public void sort_sodas()
{
    int max = sodas.Length - 1;

    for (int i = 0; i < max; i++)
    {
        int nrLeft = max - i;

        for (int j = 0; j < nrLeft; j++)
        {
            if (sodas[j+1] == null)
            {
                break;
            }
            else if (sodas[j].Price > sodas[j+1].Price)
            {
                int temp = sodas[j].Price;
                sodas[j].Price = sodas[j + 1].Price;
                sodas[j + 1].Price = temp;
            }
        }
    }

下面是冒泡排序前后的图片:

在此处输入图像描述

标签: c#arrayssortingobject

解决方案


您不应在此处更改对象的价格:

else if (sodas[j].Price > sodas[j + 1].Price)
{
    int temp = sodas[j].Price;
    sodas[j].Price = sodas[j + 1].Price;
    sodas[j + 1].Price = temp;
}

您应该更改对象位置:

else if (sodas[j].Price > sodas[j + 1].Price)
{
    var tempObject = sodas[j];
    sodas[j] = sodas[j + 1];
    sodas[j + 1] = tempObject;
}

推荐阅读