Monday 11 August 2014

Insertion sort in C#

Insertion sort:
It is a simple sorting algorithm that is relatively efficient for small lists and mostly-sorted lists, and often is used as part of more sophisticated algorithms. It works by taking elements from the list one by one and inserting them in their correct position into a new sorted list. Shell Sort is a variant of Insertion Sort, which is more efficient for larger lists because in arrays, insertion is expensive and requires shifting of all elements over by one.


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

namespace DataStructureAlgoriths
{
    class Sort
    {
public void InsertionSort()
        {
            int[] array = new int[] { 4, 9, 8, 6, 3, 2, 1 };
            int holder = 0;
            int temp = 0;
            for (int index = 1; index < array.Length; index++)
            {
                holder = index;
                temp = array[index];
                while ((holder > 0) && (array[holder - 1] > temp))
                {
                    array[holder] = array[holder - 1];
                    holder = holder - 1;
                }
                array[holder] = temp;
            }
            foreach (var item in array)
            {
                Console.WriteLine(item);
            }
        }
    }
}

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



namespace DataStructureAlgoriths
{
    class Program
    {
        static void Main(string[] args)
        {
            Sort s = new Sort();
            s.InsertionSort ();
            Console.ReadLine();
        }
    }

}

No comments:

Post a Comment