Hi, I'm just learning to use C# for the first time for a university paper and for my tutorial I'm wondering if someone could please help me with figuring out how to start modifying the sort method so that it sorts the array of integers into descending order. My code I have to modify is below.

// InsertionSort.cs
// Class that creates an array filled with random integers.  
// Provides a method to sort the array with insertion sort.
using System;

public class InsertionSort
{
   private int[] data; // array of values
   private static Random generator = new Random();

   // create array of given size and fill with random integers
   public InsertionSort( int size )
   {
      data = new int[ size ]; // create space for array

      // fill array with random ints in range 10-99
      for ( int i = 0; i < size; i++ )
         data[ i ] = generator.Next( 10, 100 );
   } // end InsertionSort constructor


   // sort array using insertion sort
   public void Sort()
   {
      int insert; // temporary variable to hold element to insert
      int moveitem; // temporary variable to store index of each successive element that must be shifted

      // loop over data.Length - 1 elements
      for ( int next = 1; next < data.Length; next++ )
      {
         // store value in current element
           insert = data[next]; // 1. SELECT ONE LINE TO PUT HERE; 

         // initialize location to place element
           moveitem = next; // 2. SELECT ONE LINE TO PUT HERE; 

         // search for place to put current element
         while ( moveitem > 0 && data[moveitem - 1] > insert )
         {
            // shift element right one slot
            data[moveitem] = data[moveitem - 1];   // 3. SELECT ONE LINE TO PUT HERE; 
            moveitem--;  // 4. SELECT ONE LINE TO PUT HERE; 
            moveitem--; 
         } // end while

         // place inserted element 
         data[moveitem] = insert;  // 5. SELECT ONE LINE TO PUT HERE; 

         PrintPass( next, moveitem ); // output pass of algorithm
      } // end for
   } // end method Sort 


   // print a pass of the algorithm
   public void PrintPass( int pass, int index )
   {
      Console.Write( "after pass {0}: ", pass );

      // output elements till swapped item
      for ( int i = 0; i < index; i++ )
         Console.Write( data[ i ] + "  " );

      Console.Write( data[ index ] + "* " ); // indicate swap

      // finish outputting array
      for ( int i = index + 1; i < data.Length; i++ )
         Console.Write( data[ i ] + "  " );
     
      Console.Write( "\n              " ); // for alignment

      // indicate amount of array that is sorted
      for( int i = 0; i <= pass; i++ )
         Console.Write( "--  " );
      Console.WriteLine( "\n" ); // skip a line in output
   } // end method PrintPass

   // method to output values in array
   public override string ToString()
   {
      string temporary = "";

      // iterate through array
      foreach ( int element in data )
         temporary += element + "  ";
     
      temporary += "\n"; // add newline character
      return temporary;
   } // end method ToString
} // end class InsertionSort

I would do it this way :

namespace ConsoleApplication1
{
    class Program
    {
        static List<int> intlist = new List<int>(); //make a list
        
        static void Main(string[] args)
        {
            intlist.Add(5); //fill the list with 5 ints
            intlist.Add(3);
            intlist.Add(5);
            intlist.Add(15);
            intlist.Add(7);

            intlist.Sort(); //sort and reverse
            intlist.Reverse();

            foreach (int i in intlist) //print on the console
            {
                Console.WriteLine(i);
            }

            Console.ReadKey(); //wait for keydown
        }
    }
}

Hi dany,
OP's demand is sorting an array elements using insertion sort algorithm.

int i, j, t;
        ....
        for (i=1; i<n; i++)
        {
            j=i;
            t=a[j];
            while (j>0 && a[j-1]>t)
            {
                a[j]=a[j-1];
                j--;
            }
            a[j]=t;
        }
Comments
great answer

welcome to daniweb jay! For your future post please use code tags when you are pasting code to the forum:

[code=c#] ...code goes here

[/code]

adatapost got it :) I removed my code, wrong approach

I took the list approach too, so I removed the code since you answered what he was looking for. I was doing:

public class InsertionSort2
  {
    private List<int> values;
    public InsertionSort2()
    {
      values = new List<int>();
    }
    public InsertionSort2(int size)
      : this()
    {
      for (int i1 = 0; i1 < size; i1++)
        values.Add(GetRandom(100));
    }
    public void Sort(bool Descending)
    {
      values.Sort();
      if (Descending)
        values.Reverse();
    }
    public static int GetRandom(int Maxvalue)
    {
      byte[] randomNumber = new byte[1];
      System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
      Gen.GetBytes(randomNumber);
      int rand = Convert.ToInt32(randomNumber[0]);
      return rand % Maxvalue + 1;
    }
    public override string ToString()
    {
      List<string> result = values.ConvertAll<string>(delegate(int i) { return i.ToString(); });
      return string.Join(" ", result.ToArray()) + Environment.NewLine;
    }
  }

I didn't want to cause confusion with my incorrect answer :P

Comments
Glad you posted it anyway!!!

Right adatapost. I should have read the OP's post more carefully:'(
Perhaps I might have done so if his code was between code tags as snake already mentioned.

Comments
You are welcome my friend

As always Scott, this is again a marvelous snippet, for a learner like me. Could you elaborate on the fact why you used RNGCryptoServiceProvider instead of the normal Random class?
Thanks in advance.

Random() is time sensitive:

If you take a look at this article:
http://msdn.microsoft.com/en-us/library/system.random.aspx

Here is what was in the help file which is slightly different than the article:

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time.

However, because the clock has finite resolution, creating different Random objects in close succession creates random number generators that produce identical sequences of random numbers. This problem can be avoided by creating a single Random object rather than multiple ones.

To improve performance, create one Random to generate many random numbers over time, instead of repeatedly creating a new Random to generate one random number.

To generate a cryptographically secure random number suitable for creating a random password, for example, use a class derived from System.Security.Cryptography..::.RandomNumberGenerator such as System.Security.Cryptography..::.RNGCryptoServiceProvider.

How are you guys getting those stars by your name anyway. In the last month every C# solver seems to have gotten one. I feel like the read-headed step child.

Don't worry Scott! I believe you have to have 1000 or 1200 posts or so.I did not take notice, suddely it was there :-O At the rate you are posting it will come soon enough.:ooh:

This article has been dead for over six months. Start a new discussion instead.