Insertion Sort Algorithm in C#

This is the simple piece of code of insertion sort algorithm. Insertion sort algorithm is less efficient as compared to other advanced algorithms but for beginner student it is a good programming practice. The insertion sort algorithm build the final sorted array one item at a time.

Source Code 

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

namespace insertionSort
{
    class Program
    {
        static void Main(string[] args)
        {
            welcomeScreen();
            Sort();
            
        }

        private static void welcomeScreen()
        {
            Console.Write("\n"
                + "\t  ======================================" + "\n"
                + "\t                  Welcome " + "\n"
                + "\t  ======================================" + "\n"
                + "\n");
        }

        private static void Sort()
        {
            int i, j, s, temp;
            int[] a = new int[20];

            Console.Write("\n"
               + "\t            Enter total elements: " + "\n"
               + "\t            ---------------------" + "\n"
               + "\t"); 
            s = Convert.ToInt32(Console.ReadLine());

            Console.Write("\tEnter " + s + " elements: "+ "\n");
            for (i = 0; i < s; i++)
            {
                Console.Write("\t");
                a[i] = Convert.ToInt32(Console.ReadLine());
            }
            for (i = 1; i < s; i++)
            {
                temp = a[i];
                j = i - 1;
                while ((j >= 0)&&(temp < a[j]) )
                {
                    a[j + 1] = a[j];
                    j = j - 1;
                }
                a[j + 1] = temp;
            }

            Console.Write("\tAfter sorting: ");
            Console.Write("\n"
               + "\t            After sorting: " + "\n"
               + "\t            -------------- " + "\n"
               + "");
            for (i = 0; i < s; i++)
            {
                Console.Write("\t" + a[i] + "\n");
            }
            int s1 = Convert.ToInt32(Console.ReadLine());
            return;
        }
    }
}

Output of the Program


Insertion Sort Algorithm in C#

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

1 comments: