Algorithms Sorting Operations


We will need a swapping operation which can be accomplished with the routine shown below:
Swap
         private void Swap<T>(T[] array, int first, int second)
        {
            T temp = array[first];
            array[first] = array[second];
            array[second] = temp;
        }
Insertion Sort
        public void InsertionSort<T> (T[] items) where T : IComparable
        {
            
           
            for (int i = 1; i < items.Length; i++)
            {
                int j = i;
                while (j > 0 && items[j].CompareTo(items[j-1]) < 0)
                {
                    Swap(items, j, j - 1);
                    j--;
                }
            }
            return;
  
        }

We have used generic operators so that sorting may be done with any type which satisfies T : IComparable, which is true of numerical and string types. The examples below show the use of this sorting function with three types.
Example
            // At console level...
            Program pgm = new Program();
            int[] integervalues = { 11100, 33, -55, 74, 0 };
            float[] floatvalues = { 3.14159F, 2.78F, 100F, -2.5F};
            string[] strvalues = { "My", "dog", "Spot", "Fibonacci", "III" };
            pgm.InsertionSort(integervalues);
            Console.WriteLine(string.Join(" | ",integervalues));
            pgm.InsertionSort(floatvalues);
            Console.WriteLine(string.Join(" | ", floatvalues));
            pgm.InsertionSort(strvalues);
            Console.WriteLine(string.Join(" | ", strvalues));
            Console.Read();


Above will produce:
-55 | 0 | 33 | 74 | 11100
-2.5 | 2.78 | 3.14159 | 100
dog | Fibonacci | III | My | Spot