Author Topic: C# Insertion Sort  (Read 807 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
C# Insertion Sort
« on: January 23, 2012, 12:44:42 am »
Here is c# code for insertion sort

Reference: http://www.softwareandfinance.com/CSharp/Insertion_Sort.html

Code: (c#)
//Source Code Listing

using System;
using System.Collections.Generic;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
 
        static int InsertionSort()
        {
            Console.Write("\nProgram for Ascending order of Numeric Values using INSERTION SORT");
            Console.Write("\n\nEnter the total number of elements: ");
            int max = Convert.ToInt32(Console.ReadLine());
 
            int [] numarray = new int[max];
 
            for(int i = 0; i < max; i++)
            {
                Console.Write("\nEnter [" + (i + 1).ToString() + "] element: ");
                numarray[i] = Convert.ToInt32(Console.ReadLine());
            }
 
            Console.Write("Before Sorting   : ");
            for(int k = 0; k < max; k++)
                Console.Write(numarray[k] + " ");
            Console.Write("\n");  
 
            for(int i = 1; i < max; i++)
            {
                int j = i;
                while(j > 0)
                {
                    if(numarray[j-1] > numarray[j])
                    {
                        int temp = numarray[j - 1];
                        numarray[j - 1] = numarray[j];
                        numarray[j] = temp;
                        j--;
                    }
                    else
                        break;
                }
                Console.Write("After iteration " + i.ToString() + ": ");
                for(int k = 0; k < max; k++)
                    Console.Write(numarray[k] + " ");
                Console.Write("/*** " + (i + 1).ToString() + " numbers from the begining of the array are input and they are sorted ***/\n");
            }
 
            Console.Write("\n\nThe numbers in ascending orders are given below:\n\n");
            for(int i = 0; i < max; i++)
            {
                Console.Write("Sorted [" + (i + 1).ToString() + "] element: ");
                Console.Write(numarray[i]);
                Console.Write("\n");
            }
            return 0;
        }
 
 
        static void Main(string[] args)
        {
            InsertionSort();
        }
    }
}

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1