简体   繁体   English

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

[英]Array.Sort doesn't work correctly in for{} loop

So, I'm trying to first make an array consisting of, let's say 5 integers.所以,我试图首先制作一个由 5 个整数组成的数组。 Going through the for loop so the user will enter each integer separately.通过 for 循环,用户将分别输入每个 integer。 However, the Array.Sort() function causes the array to be incomplete and it also replaces the last integers in the array.但是,Array.Sort() function 会导致数组不完整,并且还会替换数组中的最后一个整数。 This happens only when I try to Sort inside the 'for' loop , but sorting outside the loop works , and I can't tell why.仅当我尝试在“for”循环内进行排序时才会发生这种情况,但在循环外进行排序是有效的,我不知道为什么。 Thanks.谢谢。

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();

The problem, of course, is that you're always inserting each new element into array[index] .当然,问题在于您总是将每个新元素插入到array[index]中。 However, the sort operation is re-ordering your array, and array[index] isn't always the next unset element!但是,排序操作正在重新排序您的数组,并且array[index]并不总是下一个未设置的元素!

Let's take an example:举个例子:

Index: 0索引:0
Input number: 1输入数:1
Array: [1, 0, 0]数组: [1, 0, 0]
Sorted array: [0, 0, 1]排序数组: [0, 0, 1]

Index: 1索引:1
Input number: 2输入数:2
Array: [0, 2, 1]数组: [0, 2, 1]
Sorted array: [0, 1, 2]排序数组: [0, 1, 2]

Index: 2指数:2
Input number: 3输入数:3
Array: [0, 2, 3]数组: [0, 2, 3]
Sorted array: [0, 2, 3]排序数组: [0, 2, 3]

See what happened on that last iteration?看看最后一次迭代发生了什么? The sort operation on the previous iteration left the array containing [0, 1, 2] in that (sorted) order, but our logic said that we needed to insert the new element at index 2, which overwrite the last element in the array (giving [0, 1, 3] )!上一次迭代中的排序操作使包含[0, 1, 2]的数组以该(排序)顺序排列,但我们的逻辑表明我们需要在索引 2 处插入新元素,这会覆盖数组中的最后一个元素 (给出[0, 1, 3] )!

The key to debugging these sorts of problems is to work through your code step-by-step.调试这类问题的关键是逐步完成您的代码。 Preferably in a debugger, as this lets you look at all of your variables in each loop iteration, but you can also do it by printing out the contents of your variables and then inspecting them.最好在调试器中,因为这可以让您在每次循环迭代中查看所有变量,但您也可以通过打印出变量的内容然后检查它们来做到这一点。


One solution is not to sort your array until after your loop, as you found.如您所见,一种解决方案是在循环之后才对数组进行排序。

Another it to use a list, rather than an array.另一个它使用列表,而不是数组。 A list lets you add elements one-by-one, so you never have a situation where you're trying to sort a collection which contains some elements which have been correctly set, and some which are still waiting to be set.列表允许您一个接一个地添加元素,因此您永远不会尝试对包含一些已正确设置的元素和一些仍在等待设置的元素的集合进行排序。

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();

Notice how this also let us get rid of the if (array[j] != 0) check, since our list only contains elements which we've added so far.请注意,这也让我们摆脱了if (array[j] != 0)检查,因为我们的列表只包含我们迄今为止添加的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM