Array.Sort 在 for{} 循环中无法正常工作



所以,我试图首先创建一个由5个整数组成的数组。 通过 for 循环,以便用户将分别输入每个整数。 但是,Array.Sort() 函数会导致数组不完整,并且它还替换数组中的最后一个整数。仅当我尝试在"for"循环内排序时,才会发生这种情况,但是在循环外排序有效,我说不出原因。谢谢。

Console.WriteLine("nLive Array Sortnn");
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();

当然,问题在于您总是将每个新元素插入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 处插入新元素,这会覆盖数组中的最后一个元素(给出[0, 1, 3])!

调试此类问题的关键是逐步完成代码。最好在调试器中,因为这可以让您查看每个循环迭代中的所有变量,但您也可以通过打印出变量的内容然后检查它们来做到这一点。


一种解决方案是在循环之前不要对数组进行排序,正如您所发现的那样。

另一个它使用列表,而不是数组。列表允许您逐个添加元素,因此您永远不会遇到尝试对包含一些已正确设置的元素和一些仍在等待设置的元素的集合进行排序的情况。

Console.WriteLine("nLive Array Sortnn");
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();

请注意,这也让我们摆脱了if (array[j] != 0)检查,因为我们的列表只包含到目前为止我们添加的元素。

最新更新