Tuesday, 3 November 2015

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 it Please
asad

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

4 comments: Post Yours! Read Comment Policy!▼
Important Note:
We have Zero Tolerance to Spam. Chessy Comments and Comments with Links will be deleted immediately upon our review.

  1. thanks for creating a nice post on c programming but did you know what is conditional statement in c programming

    ReplyDelete
  2. thnks for this tutorial you my like to look at TRANSACT-SQL

    ReplyDelete
  3. thnks for this tutorial you my like to look at TRANSACT-SQL

    ReplyDelete