vendredi 9 novembre 2018

C# inserting numbers into a list box in sorted position

Excuse my nooby first post please. I am having an issue with a univerity assignment. The assignment is a "Number list manager", basically user chooses a radio button (sorted or unsorted) and when they click a button 30 numbers will be added to a list box respecting the users choice. I have no issue with the unsorted code. The lecturer specifically wants us to add the sorted numbers into the list and sort them as they are being added rather than generate the whole list and then sorting it.

if (radUnsorted.Checked == true)//if unsorted
        {
            RunChecks();
            do
            {
                numberToInput = (rnd.Next(0, 100));//sets number to input to random number
                int i = 1;

                while (i < lstNumbers.Items.Count)//loops though whole list
                {
                    if (numberToInput == Convert.ToInt32(lstNumbers.Items[i]))//checks that number doesnt already exist in list
                    {
                        numberToInput = (rnd.Next(0, 101));//genrate new random number
                        i = 0;//set to 0 to restart checking through the list
                    }
                    else//if the number isnt at i index
                    {
                        i++;//move onto next number
                    }

                }
                lstNumbers.Items.Insert(i - 1, numberToInput);//insert the number

                RunChecks();//check if the list is full
            } while (spaceLeft == true);//keep looping untill list is full


        }

This is my code to add numbers to the list in unsorted position. I've tried looking online but the only method i can see is a for loop to add the numbers to the list and then another for loop to sort them.

Here is a snippet of the criteria: You must manipulate the list during inserts and deletes using your own code and not must not utilise C# methods which undertake the task automatically e.g. inserting into an unsorted list merely requires the new value to be placed in the next available location after the current last entry whilst inserting into a sorted list requires your code to locate the insertion point and move any higher value entries to open/free up the insertion point for the inclusion of the new value.

I'm not asking for anyone to do the work for me but even pseudo-code would be very appreciated




Aucun commentaire:

Enregistrer un commentaire