簡體   English   中英

Array.Sort 在 for{} 循環中無法正常工作

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM