Friday, 24 April 2015

Insertion Shorting algorithm example in c# asp.net

Explaination:-


Although it is one of the elementary sorting algorithms with O(n2) worst-case time, insertion sort is the algorithm of choice either when the data is nearly sorted (because it is adaptive) or when the problem size is small (because it has low overhead).
For these reasons, and because it is also stable, insertion sort is often used as the recursive base case (when the problem size is small) for higher overhead divide-and-conquer sorting algorithms, such as merge sort or quick sort.

Source code example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleDemoApp
{
    class test
    {
        static void Main(string[] args)
        {
            InsertionSort();
            Console.ReadKey();
        }
        static int InsertionSort()
        {
            Console.Write("\nA INSERTION SORTING Algorithm program in c#");
            Console.Write("\n\nEnter the total number of elements of Array: ");
            int max = Convert.ToInt32(Console.ReadLine());
            int[] IntArray = new int[max];
            for (int i = 0; i < max; i++)
            {
                Console.Write("\nEnter {" + (i + 1).ToString() + "} element: ");
                IntArray[i] = Convert.ToInt32(Console.ReadLine());
            }
            Console.Write("\nArray Elements Before Sorting   : ");
            for (int k = 0; k < max; k++)
                Console.Write(IntArray[k] + " ");
            Console.Write("\n");
           for (int i = 1; i < max; i++)
            {
                int j = i;
                while (j > 0)
                {
                    if (IntArray[j - 1] > IntArray[j])
                    {
                        int temp = IntArray[j - 1];
                        IntArray[j - 1] = IntArray[j];
                        IntArray[j] = temp;
                        j--;
                    }
                    else
                        break;
                }
                Console.Write("\nArray Elements After iteration " + i.ToString() + ": \n");
                for (int k = 0; k < max; k++)
                    Console.Write(IntArray[k] + " ");
                Console.Write("\t"+(i + 1).ToString() + " Elements from the begining are sorted \n");
            }
            Console.Write("\n\nAll elements of Array are shorted below:\n\n");
            for (int i = 0; i < max; i++)
            {
                Console.Write("Sorted [" + (i + 1).ToString() + "] element of Array: ");
                Console.Write(IntArray[i]);
                Console.Write("\n");
            }
            return 0;
        }
    }
}


Output:-


No comments:

Post a Comment