【发布时间】:2017-03-15 18:37:44
【问题描述】:
我已经在 C# 中实现了插入排序算法。该方法返回一个List<List<string>>,它记录了List经历的所有步骤和更改、选择的变量等。
方法如下:
public List<List<int>> SortStepByStep(List<int> set)
{
List<List<int>> steps = new List<List<int>>();
steps.Add(set);
for (int c1 = 1; c1 < set.Count; c1++)
{
Console.WriteLine(steps[0][0].ToString());
int item = set[c1];
set.Add(item);
steps.Add(set);
set.RemoveAt(set.Count - 1);
// ^^^^ This is just to visually display what number is being selected.
set.RemoveAt(c1);
steps.Add(set);
bool inserted = false;
for (int c2 = 0; c2 < c1; c2++)
{
if ((set[c2] > item || c2 == c1 - 1) && !inserted)
{
set.Insert((set[c2] <= item && (c2 == c1 - 1) ? c2 + 1 : c2), item);
steps.Add(set);
inserted = true;
break;
// Added the break in anyway because sometimes the inserted boolean failed to work.
}
}
}
return steps;
}
该方法实际返回的只是“步骤”每个索引处的最终排序列表。我已经完成了将“步骤”写入控制台并且可以看到它逐渐变化,但不明白为什么。
其他答案提到在 for 循环中实例化,但我认为这不适用于此处。
可能是什么问题?
【问题讨论】:
-
问题是您正在向您的
steps添加一个相同的列表对象reference(它不会为您制作副本)。将 全部steps.Add(set);替换为steps.Add(set.ToList()); -
非常感谢,我不明白它是如何工作的。感谢您为我节省了很多时间!
标签: c# list for-loop instantiation insertion-sort