문제

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