Selection Sort Algorithm C#

11 12 2007

The selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled.

This is a performance improvement over the bubble sort, but the insertion sort is over twice as fast as the bubble sort and is just as easy to implement as the selection sort. In short, there really isn’t any reason to use the selection sort – use the insertion sort instead.

If you really want to use the selection sort for some reason, try to avoid sorting lists of more than a 1000 items with it or repetitively sorting lists of more than a couple hundred items.

Selection Sort Routine

// array of integers to hold values
private int[] a = new int[100];
// number of elements in array
private int x;

// Selection Sort Algorithm
public void sortArray()
{
int i, j;
int min, temp;

for( i = 0; i < x-1; i++ )
{
min = i;

for( j = i+1; j < x; j++ )
{
if( a[j] < a[min] )
{
min = j;
}
}

temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}

You can download the full code here, or the compiled code here.

for further : go Here

Advertisements