Sponsored Ad

Sunday, September 19, 2010

Selection Sort Program using C# | Selection Sort Algorithm

This is simple program to implement Selection sort algorithm in C#. You need two loops to sort all the elements of array.

 

Selection Sort Program using C# | Selection Sort Algorithm

Code to implement Selection Sort Algorithm:

using System;
using System.Text;
using System.Collections;
using System.Data;
namespace Console_App
{
    public class clsSelectionSort
    {
        public static void Main()
        {
            try
            {
                int[] SortArray = new int[200];
                Console.WriteLine("Program for Selection Sort");
                Console.WriteLine("Enter number of elements of Sorting array?");
                int NumberCount = Convert.ToInt32(Console.ReadLine());                
                Console.WriteLine(" ");
                Console.WriteLine("\nEnter integer Sorting array elements \n");
                for (int i = 0; i < NumberCount; i++)
                {
                    SortArray[i] = Convert.ToInt32(Console.ReadLine());                  
                }
                int min;

                for (int q = 0; q < NumberCount - 1; q++)
                {
                    min = q;
                    for (int i = q + 1; i < NumberCount; i++)
                    {
                        if (SortArray[min] > SortArray[i])
                            min = i;
                    }
                    if (min != q)
                    {
                        int k = SortArray[q];
                        SortArray[q] = SortArray[min];
                        SortArray[min] = k;
                    }
                }
                Console.WriteLine(" ");
                Console.WriteLine("Selection Sort Results: ");
                for (int j = 0; j < NumberCount; j++)
                    Console.WriteLine(SortArray[j]);

            }
            catch (Exception ex)
            {
                //handle exception here
            }
            Console.ReadLine();

        }
    }
}

 

To understand sorting algorithm of selection sort you can refer to Wikipedia link.

http://en.wikipedia.org/wiki/Selection_sort

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers