所以,我首先尝试创建一个由 5 个整数组成的数组。 通过 for 循环,用户将分别输入每个整数。 但是,Array.Sort() 函数会导致数组不完整,并且还会替换数组中的最后一个整数。 这种情况仅在我尝试在“for”循环内进行排序时发生,但在循环外进行排序有效,我不知道为什么。谢谢。
Console.WriteLine("\nLive Array Sort\n\n");
Console.Write("Write number of elements to sort: ");
int max = Convert.ToInt32(Console.ReadLine());
int[] array = new int[max];
for (int i = 1; i <= max; i++)
{
int index = i - 1;
Console.Write($"\nEnter Element [{i}] Index [{index}]: ");
array[index] = Convert.ToInt32(Console.ReadLine());
Console.Write("Sorted Array Elements: ");
Console.ForegroundColor = ConsoleColor.Yellow;
Array.Sort(array);
for (int j = 0; j < array.Length; j++)
{
if (array[j] != 0)
Console.Write("\t" + array[j]);
}
Console.ResetColor();
Console.Write("\n");
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nSuccessfully completed!");
Console.Read();
答案 0 :(得分:3)
当然,问题在于您总是将每个新元素插入到 array[index]
中。但是,排序操作会重新排列您的数组,array[index]
并不总是下一个未设置的元素!
举个例子:
索引:0
输入数:1
数组:[1, 0, 0]
排序数组:[0, 0, 1]
索引:1
输入数:2
数组:[0, 2, 1]
排序数组:[0, 1, 2]
索引:2
输入数:3
数组:[0, 2, 3]
排序数组:[0, 2, 3]
看看上次迭代发生了什么?前一次迭代的排序操作使包含 [0, 1, 2]
的数组以该(排序的)顺序离开,但我们的逻辑说我们需要在索引 2 处插入新元素,这会覆盖数组中的最后一个元素(给出 { {1}})!
调试这类问题的关键是逐步完成您的代码。最好在调试器中使用,因为这样可以让您在每次循环迭代中查看所有变量,但您也可以通过打印出变量的内容然后检查它们来实现。
一种解决方案是在循环之后才对数组进行排序,如您所见。
另一个它使用列表,而不是数组。列表可让您逐个添加元素,因此您永远不会遇到这样的情况:您尝试对包含一些已正确设置的元素和一些仍在等待设置的元素的集合进行排序。
[0, 1, 3]
注意这也让我们摆脱了 Console.WriteLine("\nLive Array Sort\n\n");
Console.Write("Write number of elements to sort: ");
int max = Convert.ToInt32(Console.ReadLine());
List<int> list = new List<int>();
for (int i = 1; i <= max; i++)
{
int index = i - 1;
Console.Write($"\nEnter Element [{i}] Index [{index}]: ");
list.Add(Convert.ToInt32(Console.ReadLine()));
Console.Write("Sorted List Elements: ");
Console.ForegroundColor = ConsoleColor.Yellow;
list.Sort();
for (int j = 0; j < list.Count; j++)
{
Console.Write("\t" + list[j]);
}
Console.ResetColor();
Console.Write("\n");
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nSuccessfully completed!");
Console.Read();
检查,因为我们的列表只包含我们目前添加的元素。