Insertion sort algorithm

How to solve the insertion sort algorithm in CSharp.

Insertion Sort Algorithm in C#.


Update on this page:
02/28/2010: page created.

Implementation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InsertionSort
{
    class Program
    {
        static void Main(string[] args)
        {
            InsertionSort();
            Console.ReadKey();
        }

        /// 
        /// Start Insertion Sort algorithm.
        /// 
        static void InsertionSort()
        {
            int[] sortArray = { 11, 5, 7, 8, 4, 2, 0 };

            PrintArray(sortArray);
            for (int i = 1; i < sortArray.Length; i++)
            {
                Console.WriteLine(" > pos {0}", i);
                sortArray = Insert(sortArray, i);
            }
        }

        /// 
        /// Compare the current element to the previous one, 
        /// switch position if necessary.
        /// 
        /// the current array
        /// position of the switch
        /// 
        static int[] Insert(int[] array, int position)
        {
            int temp = array[position];
            int i = position;

            while (i > 0 && (array[i] < array[i - 1]))
            {
                int tp = array[i - 1];
                array[i - 1] = array[i];
                array[i] = tp;
                i--;
                PrintArray(array);
            }
            return array;
        }

        /// 
        /// Console writeline the content of any int[].
        /// 
        /// Array to print
        static void PrintArray(int[] array)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < array.Length; i++)
            {
                sb.Append("[" + array[i].ToString() + "] ");
            }
            Console.WriteLine(sb.ToString());
        }
    }
}
                    

Related content

None yet, please be patient :)