如何解决c#选择排序是将一个对象的权重设置为另一个对象的权重,而不是将最小的升序排序为高
这是家庭作业。我的目标是创建一个选择类别,通过将动物的体重从低到高提升到给定的体重来对我的动物园中的动物进行排序。如果我说我对代码所显示的选择排序逻辑感到困惑,那我就不会诚实。
public static SortResult SelectionSortByWeight(List<Animal> animals)
{
// initialize a swap counter variable
int swapCounter = 0;
SortResult result = new SortResult();
// loop forward through the list
for (int i = 0; i < animals.Count - 1; i++)
{
// declare a variable to hold the animal with the current minimum weight
Animal a = animals[i];
// set the variable to the current animal
a = animals[i];
// loop through the remaining animals in the list to find the animal with the lowest weight
for (int j = i + 1; j < animals.Count; j++)
{
// if the weight of the current animal is less than the weight of the animal with the minimum weight,if(animals[i].Weight < animals[j].Weight)
// set the variable holding the animal with the current minimum weight to the current animal
{
animals[i].Weight = animals[j].Weight;
}
// after finding the animal with the lowest weight
// if the current animal's weight does not equal the weight of the animal with current minimum weight,swap the two animals and increment the swap count
if (animals[i].Weight != animals[j].Weight)
{
Swap(animals,j,i);
swapCounter++;
}
}
}
result.Animals = animals;
result.SwapCount = swapCounter;
return result;
}
在我到达流浪狗之前,似乎正常工作的结果是:
对正确方向的指导表示赞赏。
解决方法
这里的主要问题之一是您在执行此操作时将一只动物的重量分配给另一只动物:Multi-value - can this slot contain multiple values?
。这就是为什么最后的大多数物品都具有相同的重量。
从逻辑上讲,您可能想做的是以当前子集的最低权重存储动物的索引(按子集的意思是数组中以{{ 1}})。
我们将从外循环中的第一行开始,将if (animals[i].Weight < animals[j].Weight) animals[i].Weight = animals[j].Weight;
存储为最轻的动物,类似于:i
。然后,我们使用内部循环检查其余动物。如果在任何时候我们有i
,那么我们知道我们找到了一只较轻的动物,我们现在应该存储那个索引,例如:int minIndex = i;
内循环完成后(但仍在外循环内部),我们知道animals[j].Weight < animals[minIndex].Weight
代表以minIndex = j;
开头的子集中最轻的动物的位置。如果此索引不同于minIndex
,则我们i
。
外循环完成后,我们应该有一个选择排序的数组。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。