ideas | discover | explore

Thursday, June 28, 2012

C# 16 - Insertion Sort

Implementing a sort using insertion sort algorithm.

1. Create a new console project.
2. Edit the Program.cs inside static void Main(string[] args) file as shown below.



static void Main(string[] args)
{           
     int[] array = { 2, 3, 1, 9, 4, 7 };
     Console.Write("Before sort: ");
     PrintArray(array);
     Console.WriteLine();
     InsertionSort(array);
     Console.Write("After sort: ");
     PrintArray(array);
     Console.ReadLine();
}


private static void InsertionSort(int[] array)
{
     /*
       for i = 2:n,
            for (k = i; k > 1 and a[k] < a[k-1]; k--) 
                 swap a[k,k-1]
                 → invariant: a[1..i] is sorted
            end
     */
     for (int i = 0; i < array.Length; i++)
     {
          for (int x = i; x < 0; x--)
          {
               if (array[x] < array[x - 1])
               {
                    int temp = array[x - 1];
                    array[x - 1] = array[x];
                    array[x] = temp;
               }
           }
      }
}


private static void PrintArray(int[] array)
{
       for (int i = 0; i < array.Length; i++)
       {
            Console.Write(array[i] + " ");
       }
}


3. Press F5 to run and see the results.




4. Thank you.

References:
http://en.wikipedia.org/wiki/Insertion_sort
http://www.sorting-algorithms.com/insertion-sort

No comments: