Search code examples
c#arraysmonodevelop

How to create a loop that ask the user for two numbers, one will be for the length of the array, and the other for how many times the loop iterates


  public static void sortInterations()
    {
        Random r = new Random (); 
        Console.WriteLine ("Please enter the number of items in the array that will be sorted:");
        int numitems = Convert.ToInt32(Console.ReadLine()); 
        int[] arrayOfInts = new int[numitems];
        Console.WriteLine ("Please enter a number for iterations:");
        int iterations = Convert.ToInt32 (Console.ReadLine ());

        TimeSpan runningTime;

        for (int index = 0; index < iterations; index++) 
        {
            for (int count = 0; count < arrayOfInts.Length; count++) 
            {
                arrayOfInts [count] = r.Next (numitems);
            }
        }
        DateTime startTime = DateTime.Now;
        selectionSort (arrayOfInts);
        runningTime = DateTime.Now.Subtract(startTime);
        Console.WriteLine ("Time for ___ sort to complete: " + runningTime.ToString(@"mm\:ss\.ffffff"));
        sortInterations ();


   }

This is what i have so far! Basically i want to fill the array with random numbers and then sort it using bubble sort the number of times that the user entered in for the variable iterations and then prints out how long it took.


Solution

  • Hope this helps. You may want to get a new seed on each iteration of creating a new array of random ints to avoid getting the same or close to the same numbers.

    public static void sortInterations()
    {
      Random r = new Random();
      Console.WriteLine("Please enter the number of items in the array that will be sorted:");
      // no checking for invalid input i.e. "aA" will crash here when you try to convert 
      int numitems = Convert.ToInt32(Console.ReadLine());
      int[] arrayOfInts = new int[numitems];
      Console.WriteLine("Please enter a number for iterations:");
      // no checking for invalid input i.e. "aA" will crash here when you try to convert 
      int iterations = Convert.ToInt32(Console.ReadLine());
    
      // loop for each random array
      for (int index = 0; index < iterations; index++)
      {
        // loop to generate an array of random numbers      
        for (int count = 0; count < arrayOfInts.Length; count++)
        {
          arrayOfInts[count] = r.Next(numitems);
        }
        // a random array has been created start the clock and sort it
        Stopwatch elpased = new Stopwatch();
        elpased.Start();
        selectionSort(arrayOfInts);
        elpased.Stop();
        Console.WriteLine("Sort array Number: " + index + " Time for sort to complete in milliseconds: " + elpased.ElapsedMilliseconds.ToString());
      }
      Console.ReadLine();
    }