C# Insertion Sorting algorithm

Here is a console application to test an Insertion Sorting algorithm adapted from chapter 2 of MIT’s Introduction to Algorithms. I thought this might come in handy for any beginners, as well as a fun way to test your computer’s performance.

My desktop averages about 24.9 seconds, which, of course, depends on how scattered the integers are in the array.

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 c = 0; c < A.Length; c++)
              {
                  A = c;
              }
   
              // Random shuffle
              Random rand = new Random();
              for (int d = 0; d < A.Length; d++)
              {
                  int firstInt = A[d];
                  int swapIndex = rand.Next(initializer);
                  int secondInt = A[swapIndex];
   
                  A[d] = secondInt;
                  A[swapIndex] = firstInt;
              }
              
              //Console.Write("Array before sorting: ");
              //foreach (int number in A)
              //{
              //    Console.Write("{0} ", number);
              //}
              //Console.WriteLine("");
   
              int key;
              int i;
              int j;
   
              Console.Write("Insertion Sorting array of {0} numbers, please wait...", initializer);
              
              DateTime start = DateTime.Now;
              for (j = 1; j < A.Length; j++)
              {
                  key = A[j];
                  i = j;
   
                  while (i > 0 && A[i - 1] > key)
                  {                    
                      A[i] = A[i-1];
                      i--;
                  };
                  
                  A[i] = key;
              }
              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());
          }
      }
  }

Related Articles