简体   繁体   中英

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. Going through the for loop so the user will enter each integer separately. However, the Array.Sort() function causes the array to be incomplete and it also replaces the last integers in the array. This happens only when I try to Sort inside the 'for' loop , but sorting outside the loop works , and I can't tell why. 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] . However, the sort operation is re-ordering your array, and array[index] isn't always the next unset element!

Let's take an example:

Index: 0
Input number: 1
Array: [1, 0, 0]
Sorted array: [0, 0, 1]

Index: 1
Input number: 2
Array: [0, 2, 1]
Sorted array: [0, 1, 2]

Index: 2
Input number: 3
Array: [0, 2, 3]
Sorted array: [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] )!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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