Selection Sort Algorithm

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.
he algorithm works as follows:

  • Find the minimum value in the list
  • Swap it with the value in the first position
  • Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)

Effectively, we divide the list into two parts: the sublist of items already sorted, which we build up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.

Here is an example of this sort algorithm sorting five elements:

64 25 12 22 11

11 25 12 22 64

11 12 25 22 64

11 12 22 25 64

11 12 22 25 64
(nothing appears changed on this last line because the last)

Selection sort can also be used on list structures that make add and remove efficient, such as a Linked list In this case it's more common to remove the minimum element from the remainder of the list, and then insert it at the end of the values sorted so far. For example:

64 25 12 22 11

11 64 25 12 22

11 12 64 25 22

11 12 22 64 25

11 12 22 25 64
Source code
using System;
class selectionSort
{
public static void Main()
{
int[] a= new int[100];
int min,pass,i;
Console.WriteLine("Number of elements in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-----------------------");
Console.WriteLine(" array elements ");
Console.WriteLine("-----------------------");
for(int j=0;j<x;j++)
{
string s1=Console.ReadLine();
a[j]=Int32.Parse(s1);
}
for(pass=0;pass<x-1;pass++)
{
min=pass;
for(i=pass+1;i<x;i++)
{
if(a[min]>a[i])
min=i;
}
if( min!=pass)
{
int k=a[pass];
a[pass]=a[min];
a[min]=k;
}
}
Console.WriteLine("--------------------------------------------");
Console.WriteLine("Sorted elements of an array are(selection sort)");
for (int j=0;j<x;j++)
Console.WriteLine(a[j]);
}
}

0 comments:

Template by - Mathew | Mux99