C# Insertion Sorting alrgorithm.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace InsertionSorting
{
    class Program
    {
         static void Main(string[] args)
         {
             // int[] A = {5, 2, 4, 6, 1, 3};
             int initializer = 100000;
             int[] A = new int[initializer];
  
             for (int my = 0; my < A.Length; my++)
             {
                 A[my] = my;
             }
  
             // Random shuffle
             Random rand = new Random();
             for (int k = 0; k < A.Length; k++)
             {
                 int firstInt = A[k];
                 int swapIndex = rand.Next(initializer);
                 int secondInt = A[swapIndex];
  
                 A[k] = secondInt;
                 A[swapIndex] = firstInt;
             }
             
             //Console.Write("Array before sorting: ");
             //foreach (int number in A)
             //{
             //    Console.Write("{0} ", number);
             //}
             //Console.WriteLine("");
  
             int index;
             int j;
             int i;
  
             Console.Write("Insertion Sorting array of {0} numbers, please wait...", initializer);
             
             DateTime start = DateTime.Now;
             for (i = 1; i < A.Length; i++)
             {
                 index = A[i];
                 j = i;
  
                 while (j > 0 && A[j - 1] > index)
                 {                    
                     A[j] = A[j-1];
                     j--;
                 };
                 
                 A[j] = index;
             }
             DateTime finish = DateTime.Now;
             
             //Console.Write("Array after sorting: ");
             //foreach (int number in A)
             //{
             //    Console.Write("{0} ", number);
             //}
  
             Console.WriteLine("");
             Console.WriteLine("Duration: {0} seconds", (finish - start).ToString());
         }
     }
 }

Flattr this!

Developer James Schubert shares his code and his thoughts.