Sunday, 19 May 2013

Selection Sort Coding in Csharp

selection sortSelection Sort is the type of sorting which sorts number in proper like ascending or descending order. In the previous article we learn Bubble Sorting the working of Selection and Bubble Sort is same but the coding and algorithm is different.

The general idea of the Selection sort is that for each slot; find the element that belongs there. The Selection sort improves on the bubble sort by reducing the number of swaps.

The Operation in each pass is as follows:
  • First find the smallest element in the given user list and then swap it first position.
  • On the second step you scan through just the first N-1. Then find second smallest element in the list and swap it into the second position.
  • This process is repeated in the ending position 
  • After N-1 passes, the entire collection of data is sorted. 

Suppose the following numbers are stored in an array A:

               77, 33, 44, 11, 88, 22, 66, 55
            
            Pass 1: 77, 33, 44, 11, 88, 22, 66, 55
              Pass 2: 11, 33, 44,  77, 88,  22, 66, 55
            Pass 3: 11, 22, 44, 77, 88, 33, 66, 55
            Pass 4: 11, 22, 33, 77, 88, 44, 66, 55
            Pass 5: 11, 22, 33, 44, 88, 77, 66, 55
            Pass 6: 11, 22, 33, 44, 55, 77, 66, 88
            Pass 7: 11, 22, 33, 44, 55, 66, 77, 88

Source Code:
using System;

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

namespace lab_7_oop
{
    class Program
    {
            static void Main(string[] args)
            {
                int min = 0, temp;
                int[] a = new int[5];
                Console.WriteLine("Enter ten Integers ");
                for (int i = 0; i < 5; i++)
                {
                    a[i] = int.Parse(Console.ReadLine());
                }
                for (int i = 0; i < 5; i++)
                {
                    min = i;

                    for (int j = i + 1; j < 5; j++)
                    {
                        if (a[j] > a[min])
                        {
                            min = j;
                        }
                        temp = a[j];
                        a[j] = a[min];
                        a[min] = temp;
                    }
                    Console.WriteLine("\n" + a[i]);
                }
        }
    }
}

Output:
selection sort output