c# - 如何对数组中的对象进行冒泡排序?
问题描述
我有点问题。我正在尝试对包含对象的数组进行排序。对象是带有名称、价格和类型的瓶子。用户做出选择,他/她想要将哪个瓶子添加到阵列中。
对于作业,我们必须使用冒泡排序。我已经成功了,只是它只对价格进行排序。整个对象不只是价格本身交换位置。因此,如果 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;
}
}
}
下面是冒泡排序前后的图片:
解决方案
您不应在此处更改对象的价格:
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;
}
推荐阅读
- javascript - 我有两个数组,想通过 post 方法连接和发送数据
- wordpress - 将 wpdb 包装在 try 和 cach 中
- angular - 我可以在一个 Nx 工作区中将 NX CLI 用于 Angular 和 React 应用程序吗?
- angular - 我在 Angular 中使用了两个或多个模块,如何使用找不到页面的组件设置路由模块
- javascript - 如何在“ng build --prod”之后让我的 Angular 应用程序使用编辑过的配置文件
- utf-8 - 鼻子 - Nosetests 在第一次尝试时运行,但在所有进一步的尝试中都失败
- java - 使用流使用来自另一个列表的值填充地图的值
- python - Django 请求方法总是返回 GET
- javascript - 如何在sharepoint中计算项目进度
- mongodb - 当导入的文档具有相同的 id 时替换 MongoDB 中的文档 (mongoimport)