[英]Array.Sort doesn't work correctly in for{} loop
所以,我试图首先制作一个由 5 个整数组成的数组。 通过 for 循环,用户将分别输入每个 integer。 但是,Array.Sort() function 会导致数组不完整,并且还会替换数组中的最后一个整数。 仅当我尝试在“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();
当然,问题在于您总是将每个新元素插入到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 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();
请注意,这也让我们摆脱了if (array[j] != 0)
检查,因为我们的列表只包含我们迄今为止添加的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.