How can I run the Insertion Sort code after each time user enters a value. Please notice that I don't have much knowledge about programming so showing an example or ready to use code would be appreciated.

    Console.Write("How long the Insertion sort list should be?: ");
    var countString = Console.ReadLine();
    int count = Convert.ToInt32(countString);
    int[] data = new int[count];

    for (int i = 0; i < count; i++)
    {

        var input = Console.ReadLine();
        data[i] = Convert.ToInt32(input);

        Console.WriteLine(input); // << HERE THE SORTING SHOULD HAPPEN AFTER EACH VALUE THAT I ADD.

    }


    int j = 0;
    int help = 0;

    for (int i = 1; i < data.Length; i++) 
    {
        j = i;
        help = data[i];

        while (j > 0 && help < data[j - 1])
        {
            data[j] = data[j - 1];
            j--;
        }

        data[j] = help;
    }

    foreach (var i in data)
    {
        Console.Write("{0}, ", i);
    }
}
有帮助吗?

解决方案

You can visually divide your code into two parts. The first part is for inserting the values. The second part sorts these values. So you have to cut the second part and insert at the place, where sorting should happen, I hope you will find this place ;)

Also think that you should replace i in the second for with something else, for example with k

Good luck

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top